如何获取本地文件的正确URI?

3
令我大为惊讶的是,在jdk1.8.0_u144上,以下代码片段会打印出false
public class Tmp {
  public static void main(String[] args) {
    File f = new File(".");
    boolean result = f.toPath().toUri().toString().equals(f.toURI().toString());
    System.out.println("result = " + result);
  }
}

显然,java.io.File#toURIjava.nio.Path#toUri返回不同的表示方式。问题是,哪个是正确的(根据RFC 8089)?


File.toURI 是正确的。您可以通过在比较之前打印两个值来手动验证。 - Optional
1个回答

3
TLDR版本:根据RFC 8089,URI的两种形式都是正确的。您的示例代码突出了给定文件的Path的toUri()和File的toURI()方法返回值之间的区别。在我的Win10机器上打印这些值显示为: path.toUri() => file:///D:/NetBeansProjects/MiscTests/./
file.toUri() => file:/D:/NetBeansProjects/MiscTests/./
Linux上的结果类似: path.toUri() => file:///home/johndoe/IdeaProjects/TestUri/./
file.toUri() => file:/home/johndoe/IdeaProjects/TestUri/./
因此,唯一的区别是URI中“file:”后面跟随的单斜杠或三个斜杠。
从您的链接中,RFC 8089的附录B确认了这两种形式都是有效的URI。

A traditional file URI for a local file with an empty authority. This is the most common format in use today. For example:

  *  "file:///path/to/file"

o The minimal representation of a local file with no authority field and an absolute path that begins with a slash "/". For example:

  *  "file:/path/to/file"
进一步确认两种URI格式都是有效的,因为可以在浏览器中输入任意一种格式来显示目录的内容。然而,有几点值得注意:
  • Brave是唯一不接受单斜杠形式URI(由File.toURI().toString()给出)的浏览器。

  • 所有浏览器都接受三个斜杠形式的URI(由File.toPath().toUri().toString()给出)。

  • 如果我在浏览器的地址栏中输入带有一个斜杠的URI,则会将其转换为三个斜杠。

  • 奇怪的是,Chrome和Firefox将接受URI中的任意数量的斜杠(例如file:///////////D:/NetBeansProjects/MiscTests/),并仍然显示目录。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接