在URL和Windows文件名(Java)之间转换? [英] Convert between URL and windows filename (Java)?
问题描述
在Java中,是否有标准/好的方式在URL和Windows文件名之间进行转换?
Is there a standard/good way of converting between urls and windows filenames, in Java?
我正在尝试下载文件,但我希望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.
我当前的hacky解决方案是替换非法字符(例如作为'?')具有特定字符串(例如'QQ'),但这使得转换回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?
推荐答案
你可能比使用 URLEncoder 对URL进行编码:
You could do worse than use URLEncoder to encode the 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);
文件名成为合法的win32名称:
The filename becomes the legal win32 name:
http%3A%2F%2F172.0.0.1%3A80%2Ffoo%2Fbar%2Fbaz.txt%3Fblack%3Dwhite
这是一个可逆的操作:
String original = URLDecoder.decode(filename, "UTF-8");
这篇关于在URL和Windows文件名(Java)之间转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!