Java:Windows 文件上的 File.toURI().toURL()
我运行的系统是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的Authority部分为null或空,因此双斜杠被跳过。 那么 URL 的权限部分是什么?文件协议中真的不存在它吗?
The system I'm running on is Windows XP, with JRE 1.6.
I do this :
public static void main(String[] args) {
try {
System.out.println(new File("C:\\test a.xml").toURI().toURL());
} catch (Exception e) {
e.printStackTrace();
}
}
and I get this : file:/C:/test%20a.xml
How come the given URL doesn't have two slashes before the C:
? I expected file://C:...
. Is it normal behaviour?
EDIT :
From Java source code : java.net.URLStreamHandler.toExternalForm(URL)
result.append(":");
if (u.getAuthority() != null && u.getAuthority().length() > 0) {
result.append("//");
result.append(u.getAuthority());
}
It seems that the Authority part of a file URL is null or empty, and thus the double slash is skipped. So what is the authority part of a URL and is it really absent from the file protocol?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个有趣的问题。
首先,我在 JRE6 上得到了相同的结果。 当我删除 toURL() 部分时我什至得到了这一点。
RFC2396 实际上不需要两个斜杠。 根据第 3 节:
话虽如此,RFC2396 已被 RFC3986 取代,其中指出
那么,就这样吧。 由于文件 URI 没有权限段,因此禁止它们以 // 开头。
然而,该 RFC 直到 2005 年才出现,而 Java 引用了 RFC2396,所以我不知道为什么它遵循这个约定,因为新 RFC 之前的文件 URL 总是有两个斜杠。
That's an interesting question.
First things first: I get the same results on JRE6. I even get that when I lop off the toURL() part.
RFC2396 does not actually require two slashes. According to section 3:
Having said that, RFC2396 has been superseded by RFC3986, which states
So, there you go. Since file URIs have no authority segment, they're forbidden from starting with //.
However, that RFC didn't come around until 2005, and Java references RFC2396, so I don't know why it's following this convention, as file URLs before the new RFC have always had two slashes.
要回答为什么可以同时拥有两者:
RFC3986 (3.2.2. Host) 指出:
因此,“文件”方案将
file:///path/file
转换为具有最终用户计算机的上下文,即使权限是空主机也是如此。To answer why you can have both:
RFC3986 (3.2.2. Host) states:
So the "file" scheme translates
file:///path/file
to have a context of the end-user's machine even though the authority is an empty host.至于在浏览器中使用它,这并不重要。 我通常会看到
file:///...
但一个、两个或三个“/”都可以。 这让我认为(无需查看 java 文档)这将是正常行为。As far as using it in a browser is concerned, it doesn't matter. I have typically seen
file:///...
but one, two or three '/' will all work. This makes me think (without looking at the java documentation) that it would be normal behavior.