Java:如何从转义的URL获取文件? [英] Java: how to get a File from an escaped URL?

查看:454
本文介绍了Java:如何从转义的URL获取文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在收到一个找到本地文件的URL(事实上,我收到一个URL不在我的控制之下)。 URL按照RFC2396中的定义有效转义。如何将其转换为Java File对象?



有趣的是,getFile()方法的URL返回一个String,而不是一个File。



我创建了一个名为/ tmp / some dir的目录(间距为some和dir之间),通过以下URL正确定位:file: // tmp / some%20dir(为了清楚起见,引用了引号。)



如何将该URL转换为Java文件?



要提供有关我的问题的更多详细信息,以下内容将输出false:

  URL url = new URL( file:/// tmp / some%20dir); 
文件f = new File(url.getFile());
System.out.println(dir exists?+ f.exists());

虽然以下(用空格手动替换%20)打印true:

  URL url = new URL(file:/// tmp / some%20dir); 
文件f = new File(url.getFile()。replaceAll(%20,));
System.out.println(dir exists?+ f.exists());

请注意,我不是问为什么第一个例子打印错误为什么第二个例子使用我的hacky replaceAll 打印真实,我在问如何将转义的URL转换为Java File对象。



编辑:感谢所有,这几乎是一个欺骗,但不完全。



愚蠢的我正在寻找一个帮助方法在URL类本身内。



以下工作原理是从Java网址获取Java文件:



<$ URL $ url = new URL(file:/// home / nonet / some%20dir);
文件f = new File(URLDecoder.decode(url.getFile(),UTF-8));


解决方案

  URLDecoder。 decode(url); // deprecated 
URLDecoder.decode(url,UTF-8); //使用它而不是

查看相关问题如何在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

See related question How do you unescape URLs in Java?

这篇关于Java:如何从转义的URL获取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆