Windows 文件上的 Java : File. toURI().toURL()

标签 java url uri filepath file-uri

我运行的系统是 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/

相关文章:

用于防御性编码的 Wil Shipley 的 `IsEmpty` 方法的 Java 实现

java - 如何使用 MyBatis 与 Spring 集成将 unicode 插入 Oracle NVARCHAR

http - HTTP 重定向代码之间的区别

c# - Path.Combine 是否曾在 .net 中进行过网络调用?

java - 出现不明字符时,如何将URL转为URI?

java - 如何在黑莓应用程序中制作屏幕转换效果?

java - 在 Java 中从 PostgreSQL 检索 xml 数组

android - 从 URL 加载图像并保存在 android 内存中

php - 与 PHP 对话从 Android 应用程序获取命令

javascript - Jquery: div 超链接