我有一个 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)
构造函数。
最佳答案
new File(URI)
根据 URI#getPath()
获得的路径构建文件而不是 - 你所期望的 - URI#getRawPath()
.这看起来像是“设计使然”的功能。
你有两个选择:
- 运行
URLEncoder#encode()
在fn
上两次(注意:encode()
,而不是encoder()
)。 - 使用
new File(String)
相反。
关于java - 为什么 Java 会自动解码 URI 编码文件名中的 %2F?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2765782/