java 文件 url,Java:如何从转义的URL获取文件?

I'm receiving an URL that locates a local file (the fact that I receive an URL is not in my control). The URL is escaped validly as defined in RFC2396. How can I transform this to a Java File object?

Funnily enough, the URL getFile() method returns a String, not a File.

I've created a directory called "/tmp/some dir" (with a spacing character between "some" and "dir"), which is correctly located by the following URL: "file:///tmp/some%20dir" (quotes added for clarity).

How can I convert that URL to a Java File?

To give more detail about my issue, the following prints false:

URL url = new URL( "file:///tmp/some%20dir" );

File f = new File( url.getFile() );

System.out.println( "Does dir exist? " + f.exists() );

While the following (manually replacing "%20" with a space) prints true:

URL url = new URL( "file:///tmp/some%20dir" );

File f = new File( url.getFile().replaceAll( "%20", " " ) );

System.out.println( "Does dir exist? " + f.exists() );

Note that I'm not asking why the first example prints false nor why the second example using my hacky replaceAll prints true, I'm asking how to convert an escaped URL into a Java File object.

EDIT: thanks all, this was nearly a dupe but not exactly.

Stupidly I was looking for a helper method inside the URL class itself.

The following works as expected to get a Java File from a Java URL:

URL url = new URL( "file:///home/nonet/some%20dir" );

File f = new File( URLDecoder.decode( url.getFile(), "UTF-8" ) );

解决方案

URLDecoder.decode(url);//deprecated

URLDecoder.decode(url, "UTF-8"); //use this instead

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值