我运行的系统是 Windows XP,带有 JRE 1.6。
我这样做:
public static void main(String[] args) {
try {
System.out.println(new File("C:\\test a.xml").toURI().toURL());
} catch (Exception e) {
e.printStackTrace();
}
}
我得到这个:file:/C:/test%20a.xml
为什么给定的 URL 在 C:
之前没有两个斜杠?我期望 file://C:...
。这是正常行为吗?
编辑:
来自 Java 源代码:java.net.URLStreamHandler.toExternalForm(URL)
result.append(":");
if (u.getAuthority() != null && u.getAuthority().length() > 0) {
result.append("//");
result.append(u.getAuthority());
}
似乎文件 URL 的权限部分为 null 或为空,因此跳过了双斜杠。那么什么是 URL 的权限部分,它真的不存在于文件协议(protocol)中吗?
最佳答案
这是个有趣的问题。
首先要做的是:我在 JRE6 上得到了相同的结果。当我去掉 toURL() 部分时,我什至明白了这一点。
RFC2396实际上不需要两个斜杠。根据第 3 节:
The URI syntax is dependent upon the scheme. In general, absolute URI are written as follows:
<scheme>:<scheme-specific-part>
话虽如此,RFC2396 已被 RFC3986 取代, 说明
The generic URI syntax consists of a hierarchical sequence of omponents referred to as the scheme, authority, path, query, and fragment.
URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ] hier-part = "//" authority path-abempty / path-absolute / path-rootless / path-empty
The scheme and path components are required, though the path may be empty (no characters). When authority is present, the path must either be empty or begin with a slash ("/") character. When authority is not present, the path cannot begin with two slash characters ("//"). These restrictions result in five different ABNF rules for a path (Section 3.3), only one of which will match any given URI reference.
所以,你去吧。由于文件 URI 没有权限段,因此禁止以//开头。
但是,那个 RFC 直到 2005 年才出现,并且 Java 引用了 RFC2396,所以我不知道为什么要遵循这个约定,因为新 RFC 之前的文件 URL 总是有两个斜杠。
关于Windows 文件上的 Java : File. toURI().toURL(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1131273/