将 URL 转换为普通的 Windows 文件名 Java [英] Convert URL to normal windows filename Java

查看:23
本文介绍了将 URL 转换为普通的 Windows 文件名 Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法转换这个:

/C:/Users/David/Dropbox/My%20Programs/Java/Test/bin/myJar.jar

进入这个?:

C:UsersDavidDropboxMy ProgramsJavaTestinmyJar.jar

我正在使用以下代码,它将返回 .JAR 存档或/bin 目录的完整路径.

I am using the following code, which will return the full path of the .JAR archive, or the /bin directory.

fullPath = new String(MainInterface.class.getProtectionDomain()
            .getCodeSource().getLocation().getPath());

问题是,getLocation() 返回一个 URL,我需要一个普通的 Windows 文件名.我尝试在 getLocation() 之后添加以下内容:

The problem is, getLocation() returns a URL and I need a normal windows filename. I have tried adding the following after getLocation():

toString()toExternalForm() 都返回:

file:/C:/Users/David/Dropbox/My%20Programs/Java/Test/bin/

getPath() 返回:

/C:/Users/David/Dropbox/My%20Programs/Java/Test/bin/

注意 %20 应该转换为空格.

Note the %20 which should be converted to space.

有没有一种快速简便的方法来做到这一点?

Is there a quick and easy way of doing this?

推荐答案

当前的建议(使用 JDK 1.7+)是转换 URL → URI → 路径.因此,要将 URL 转换为文件,您应该说 Paths.get(url.toURI()).toFile().如果你还不能使用 JDK 1.7,我会推荐 new File(URI.getSchemeSpecificPart()).

The current recommendation (with JDK 1.7+) is to convert URL → URI → Path. So to convert a URL to File, you would say Paths.get(url.toURI()).toFile(). If you can’t use JDK 1.7 yet, I would recommend new File(URI.getSchemeSpecificPart()).

转换文件 → URI:首先,我将向您展示一些您可能会在 Java 中获得的 URI 的示例.

Converting file → URI: First I’ll show you some examples of what URIs you are likely to get in Java.

                          -classpath URLClassLoader File.toURI()                Path.toUri()
C:Program Files          file:/C:/Program%20Files/ file:/C:/Program%20Files/   file:///C:/Program%20Files/
C:main.c++               file:/C:/main.c++         file:/C:/main.c++           file:///C:/main.c++
\VBOXSVRDownloads       file://VBOXSVR/Downloads/ file:////VBOXSVR/Downloads/ file://VBOXSVR/Downloads/
C:Résume.txt             file:/C:/R%c3%a9sume.txt  file:/C:/Résume.txt         file:///C:/Résume.txt
\?C:Windows (non-path) file://%3f/C:/Windows/    file:////%3F/C:/Windows/    InvalidPathException

关于这些 URI 的一些观察:

Some observations about these URIs:

  • URI 规范是 RFC 1738:URL,由 RFC 2396:URI,由 RFC 3986:URI.(WHATWG 也有一个 URI 规范,但它没有指定文件 URI 应该如何解释.) 路径中的任何保留字符都用百分比引用,当您调用 URI.toASCIIString() 时,URI 中的非 ascii 字符用百分比引用.
  • File.toURI() 比 Path.toUri() 差,因为 File.toURI() 返回一个不寻常的非 RFC 1738 URI(提供 file:/而不是 file:///)并且不格式化 URI根据 Microsoft 的 UNC 路径首选格式.但是,这些 UNC URI 在 Firefox 中都不起作用(Firefox 需要 file://///).
  • Path 比 File 更严格;您不能从 ."前缀.这些前缀不用作路径本身的一部分",但它们可以传递给 Win32 API.
  • The URI specifications are RFC 1738: URL, superseded by RFC 2396: URI, superseded by RFC 3986: URI. (The WHATWG also has a URI spec, but it does not specify how file URIs should be interpreted.) Any reserved characters within the path are percent-quoted, and non-ascii characters in a URI are percent-quoted when you call URI.toASCIIString().
  • File.toURI() is worse than Path.toUri() because File.toURI() returns an unusual non-RFC 1738 URI (gives file:/ instead of file:///) and does not format URIs for UNC paths according to Microsoft’s preferred format. None of these UNC URIs work in Firefox though (Firefox requires file://///).
  • Path is more strict than File; you cannot construct an invalid Path from "." prefix. "These prefixes are not used as part of the path itself," but they can be passed to Win32 APIs.

转换 URI → 文件:让我们尝试将前面的示例转换为文件:

Converting URI → file: Let’s try converting the preceding examples to files:

                            new File(URI)            Paths.get(URI)           new File(URI.getSchemeSpecificPart())
file:///C:/Program%20Files  C:Program Files         C:Program Files         C:Program Files
file:/C:/Program%20Files    C:Program Files         C:Program Files         C:Program Files
file:///C:/main.c++         C:main.c++              C:main.c++              C:main.c++
file://VBOXSVR/Downloads/   IllegalArgumentException \VBOXSVRDownloads     \VBOXSVRDownloads
file:////VBOXSVR/Downloads/ \VBOXSVRDownloads      \VBOXSVRDownloads     \VBOXSVRDownloads
file://///VBOXSVR/Downloads \VBOXSVRDownloads      \VBOXSVRDownloads     \VBOXSVRDownloads
file://%3f/C:/Windows/      IllegalArgumentException IllegalArgumentException \?C:Windows
file:////%3F/C:/Windows/    \?C:Windows           InvalidPathException     \?C:Windows

同样,使用 Paths.get(URI) 优于 new File(URI),因为 Path 能够处理 UNC URI 并拒绝无效路径? 字首.但是,如果您不能使用 Java 1.7,请改用 new File(URI.getSchemeSpecificPart()).

Again, using Paths.get(URI) is preferred over new File(URI), because Path is able to handle the UNC URI and reject invalid paths with the ? prefix. But if you can’t use Java 1.7, say new File(URI.getSchemeSpecificPart()) instead.

顺便说一句,不要不要使用 URLDecoder 来解码文件 URL.对于包含+"的文件,例如file:///C:/main.c++",URLDecoder 会将其转为C:main.c "!URLDecoder 仅用于解析 URI 查询中的 application/x-www-form-urlencoded HTML 表单提交 (param=value&param=value),而不用于取消引用 URI 的路径.

By the way, do not use URLDecoder to decode a file URL. For files containing "+" such as "file:///C:/main.c++", URLDecoder will turn it into "C:main.c  "! URLDecoder is only for parsing application/x-www-form-urlencoded HTML form submissions within a URI’s query (param=value&param=value), not for unquoting a URI’s path.

2014-09:编辑以添加示例.

2014-09: edited to add examples.

这篇关于将 URL 转换为普通的 Windows 文件名 Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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