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

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

问题描述

我收到一个用于定位本地文件的 URL(我无法控制收到 URL 的事实).URL 按照 RFC2396 中的定义进行有效转义.如何将其转换为 Java File 对象?

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?

有趣的是,URL getFile() 方法返回一个字符串,而不是一个文件.

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

我创建了一个名为/tmp/some dir"的目录(some"和dir"之间有一个空格字符),它可以通过以下 URL 正确定位:file:///tmp/some%20dir"(为清楚起见添加了引号).

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

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

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

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

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

请注意,我不是在问为什么第一个示例打印 false 也为什么使用我的 hacky replaceAll 打印的第二个示例打印 true,我我在问如何将转义的 URL 转换为 Java File 对象.

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.

愚蠢的是,我正在 URL 类本身中寻找一个辅助方法.

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

以下按预期工作以从 Java URL 获取 Java 文件:

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

请参阅相关问题 您如何在 Java 中对 URL 进行转义?

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

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