Java为什么会自动解码URI编码的文件名中的%2F? [英] Why does Java automatically decode %2F in URI encoded filenames?
问题描述
我有一个servlet,需要写出具有用户可配置名称的文件。我正在尝试使用URI编码正确地转义特殊字符,但是JRE似乎会自动将编码后的斜杠%2F
转换为路径分隔符。
I have a servlet that needs to write out files that have a user-configurable name. I am trying to use URI encoding to properly escape special characters, but the JRE appears to automatically convert encoded forward slashes %2F
into path separators.
示例:
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
序列会自动转换为正斜杠,并且我最终得到了错误的路径。有人知道解决此问题的正确方法吗?
After the new File object is instantiated, the %2F
sequence is automatically converted to a forward slash and I end up with an incorrect path. Does anybody know the proper way to approach this issue?
问题的核心似乎是
uri.equals( new File(uri).toURI() ) == FALSE
URI中的c $ c>%2F 。
when there is a %2F
in the URI.
我打算逐字使用URLEncoded字符串,而不是尝试使用 File(uri)
构造函数。
I'm planning to just use the URLEncoded string verbatim rather than trying to use the File(uri)
constructor.
推荐答案
新文件( URI)
根据 URI#getPath()
而不是-您所期望的- URI#getRawPath()
。这看起来像通过设计功能。
The new File(URI)
constructs the file based on the path as obtained by URI#getPath()
instead of -what you expected- URI#getRawPath()
. This look like a feature "by design".
您有2个选择:
- 运行 <$ c
fn
上的$ c> URLEncoder#encode() (请注意:encode()
,而不是encoder()
)。 - 使用
新文件(字符串)
。
- Run
URLEncoder#encode()
onfn
twice (note:encode()
, notencoder()
). - Use
new File(String)
instead.
这篇关于Java为什么会自动解码URI编码的文件名中的%2F?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!