java Uri 编解码,Java为什么会自动解码URI编码的文件名中的%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.

Example:

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() );

The output is:

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

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?

The core of the problem seems to be that

uri.equals( new File(uri).toURI() ) == FALSE

when there is a %2F in the URI.

I'm planning to just use the URLEncoded string verbatim rather than trying to use the File(uri) constructor.

解决方案

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".

You have 2 options:

Run URLEncoder#encode() on fn twice (note: encode(), not encoder()).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值