Java 将 URL 转换为绝对路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3631623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 02:59:02  来源:igfitidea点击:

Convert URL to AbsolutePath

javaurlfile-io

提问by nite

Is there any easy way to convert a URL that contains to two-byte characters into an absolute path?

有没有什么简单的方法可以将包含两字节字符的 URL 转换为绝对路径?

The reason I ask is I am trying to find resources like this:

我问的原因是我试图找到这样的资源:

URL url=getClass().getResources("/getresources/test.txt");
String path=url.toString();
File f=new File(path);

The program can't find the file. I know the path contain '%20' for all spaces which I could convert but my real problem is I'm using a japanese OS and when the program jar file is in a directory with japanese text (for example デスクトップ) I get the URL-encodingof the directory name, like this:

程序找不到文件。我知道路径包含我可以转换的所有空格的“%20”,但我真正的问题是我使用的是日语操作系统,当程序 jar 文件位于带有日语文本的目录中时(例如 デスクトップ),我得到了URL- 目录名称的编码,如下所示:

%e3%83%87%e3%82%b9%e3%82%af%e3%83%88%e3%83%83%e3%83%97

%e3%83%87%e3%82%b9%e3%82%af%e3%83%88%e3%83%83%e3%83%97

I think I could get the UTF-8 byte codes and convert this into the proper characters to find the file, but I'm wondering if there is an easier way to do this. Any help would be greatly appreciated.

我想我可以获得 UTF-8 字节码并将其转换为正确的字符来查找文件,但我想知道是否有更简单的方法来做到这一点。任何帮助将不胜感激。

nt

nt

采纳答案by Noel Ang

URL url=getClass().getResource("/getresources/test.txt");
File f=new File(url.toURI());

回答by Moritz

Filehas a constructor taking an argument of type java.net.URIfor this case:

Filejava.net.URI对于这种情况,有一个构造函数采用类型参数:

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

回答by Mincong Huang

If you were interested in getting Pathfrom URL, you can do:

如果您有兴趣Path从 URL获取,您可以执行以下操作:

Path p = Paths.get(url.toURI());