【发布时间】:2010-05-04 13:41:46
【问题描述】:
我有一个 servlet,它需要写出具有用户可配置名称的文件。我正在尝试使用 URI 编码来正确转义特殊字符,但 JRE 似乎会自动将编码的正斜杠 %2F 转换为路径分隔符。
例子:
File dir = new File("C:\Documents and Setting\username\temp");
String fn = "Top 1/2.pdf";
URI uri = new URI( dir.toURI().toASCIIString() + URLEncoder.encoder( fn, "ASCII" ).toString() );
File out = new File( uri );
System.out.println( dir.toURI().toASCIIString() );
System.out.println( URLEncoder.encode( fn, "ASCII" ).toString() );
System.out.println( uri.toASCIIString() );
System.out.println( output.toURI().toASCIIString() );
输出是:
file:/C:/Documents%20and%20Settings/username/temp/
Top+1%2F2.pdf
file:/C:/Documents%20and%20Settings/username/temp/Top+1%2F2.pdf
file:/C:/Documents%20and%20Settings/username/temp/Top+1/2.pdf
实例化新的 File 对象后,%2F 序列会自动转换为正斜杠,我最终会得到一个不正确的路径。有人知道解决这个问题的正确方法吗?
问题的核心似乎在于
uri.equals( new File(uri).toURI() ) == FALSE
当 URI 中有 %2F 时。
我打算逐字使用 URLEncoded 字符串,而不是尝试使用 File(uri) 构造函数。
【问题讨论】:
-
这样做当然是正确的。如果您在文件名中需要逐字逐句
%2F,则在 URI 中使用时必须正确转义:%252F -
我想你误会了。我不想对“%2F”进行编码,我想对“/”进行编码,以便创建一个合法的文件名,该文件名代表包含正斜杠的用户指定名称。
-
出于兴趣:我知道这些是文件 URI,但如果它们是 http URI,网络服务器不应该处理
%F2和/相同吗?另外:由于/在 Windows 文件名中无效,因此这样的文件 URI 似乎没有意义,或者? -
@RoToRa:直截了当,他只是想要在文件名中使用 URL 编码字符的能力。这不能正常工作,因为
new File(URI)会解码它们。