令我惊讶的是,以下代码片段在 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#toURI
和 java.nio.Path#toUri
返回不同的表示形式。问题是,哪一个是正确的(根据 RFC 8089 )?
最佳答案
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() => 文件:/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/),并且仍然显示目录.
关于java - 如何获取本地文件的正确URI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46610910/