在 URL 和 Windows 文件名(Java)之间转换?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1652483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 13:21:59  来源:igfitidea点击:

Convert between URL and windows filename (Java)?

javawindowsfileurl

提问by Paul

Is there a standard/good way of converting between urls and windows filenames, in Java?

在 Java 中,是否有在 url 和 windows 文件名之间进行转换的标准/好方法?

I am trying to download files, but I want the windows filename to be convertible back to the original filename. Note that the query portion of the url is vital, as I will be downloading different pages that differ only in query.

我正在尝试下载文件,但我希望 Windows 文件名可以转换回原始文件名。请注意,url 的查询部分至关重要,因为我将下载仅在查询上有所不同的不同页面。

My current hacky solution is to replace illegal characters (such as '?') with a specific string (such as 'QQ'), but this makes conversion back to url less transparent. Is there a better way?

我目前的 hacky 解决方案是用特定的字符串(例如 'QQ')替换非法字符(例如 '?'),但这会使转换回 url 的透明度降低。有没有更好的办法?

回答by McDowell

You could do worse than use URLEncoderto encode the URL:

您可能比使用URLEncoder对 URL 进行编码更糟糕:

String url = "http://172.0.0.1:80/foo/bar/baz.txt?black=white";
String filename = URLEncoder.encode(url, "UTF-8");
File file = new File(filename);

The filename becomes the legal win32 name:

文件名成为合法的 win32 名称:

http%3A%2F%2F172.0.0.1%3A80%2Ffoo%2Fbar%2Fbaz.txt%3Fblack%3Dwhite

This is a reversible operation:

这是一个可逆操作:

String original = URLDecoder.decode(filename, "UTF-8");

回答by Jé Queue

The java.io.File class takes a URI &| filename as a constructor, but contains toURI()& toURL()methods as well as getName()& getPath(). I assume this would be a valid conversion for you?

java.io.File 类采用 URI &| filename 作为构造函数,但包含toURI()&toURL()方法以及getName()& getPath()。我认为这对你来说是一个有效的转换?

回答by Paulius

But is it possible to encode url to filename at all? I mean, can there be the 100% valid solution? I think that converting url to filename is the wrong idea in general, because of different limitations set on urls and filenames:

但是有可能将 url 编码为文件名吗?我的意思是,可以有 100% 有效的解决方案吗?我认为将 url 转换为文件名通常是错误的想法,因为对 url 和文件名设置了不同的限制:

Max filename length (NTFS filesystem, Unicode, using UTF-16 encoding) - 255

最大文件名长度(NTFS 文件系统,Unicode,使用 UTF-16 编码)- 255

Max URL length (using UTF-8 encoding?) - 2000 chars

最大 URL 长度(使用 UTF-8 编码?) - 2000 个字符

回答by OscarRyz

If you mean to convert an URL encoded to non encoder you could use:

如果您打算将编码的 URL 转换为非编码器,您可以使用:

URLDecoder

网址解码器

Utility class for HTML form decoding. This class contains static methods for decoding a String from the application/x-www-form-urlencoded MIME format.

用于 HTML 表单解码的实用程序类。此类包含用于从 application/x-www-form-urlencoded MIME 格式解码字符串的静态方法。

See if that's what you need.

看看这是否是你需要的。