Java 中的 getPath()、getAbsolutePath() 和 getCanonicalPath() 之间有什么区别? [英] What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?
问题描述
Java 中的 getPath()
、getAbsolutePath()
和 getCanonicalPath()
有什么区别?
What's the difference between getPath()
, getAbsolutePath()
, and getCanonicalPath()
in Java?
我什么时候使用每一个?
And when do I use each one?
推荐答案
考虑这些文件名:
C: empfile.txt
- 这是一个路径、一个绝对路径和一个规范路径.
C: empfile.txt
- This is a path, an absolute path, and a canonical path.
.file.txt
- 这是一个路径.它既不是绝对路径,也不是规范路径.
.file.txt
- This is a path. It's neither an absolute path nor a canonical path.
C: empmyappin..\..file.txt
- 这是一个路径和一个绝对路径.这不是规范路径.
C: empmyappin..\..file.txt
- This is a path and an absolute path. It's not a canonical path.
规范路径始终是绝对路径.
A canonical path is always an absolute path.
从路径转换为规范路径使其成为绝对路径(通常附加在当前工作目录上,因此例如 ./file.txt
变为 c:/temp/file.txt代码>).文件的规范路径只是净化"路径,删除和解析诸如
..
之类的内容并解析符号链接(在 unix 上).
Converting from a path to a canonical path makes it absolute (usually tack on the current working directory so e.g. ./file.txt
becomes c:/temp/file.txt
). The canonical path of a file just "purifies" the path, removing and resolving stuff like ..
and resolving symlinks (on unixes).
另请注意以下带有 nio.Paths 的示例:
Also note the following example with nio.Paths:
String canonical_path_string = "C:\Windows\System32\";
String absolute_path_string = "C:\Windows\System32\drivers\..\";
System.out.println(Paths.get(canonical_path_string).getParent());
System.out.println(Paths.get(absolute_path_string).getParent());
虽然两个路径都指向同一个位置,但输出会大不相同:
While both paths refer to the same location, the output will be quite different:
C:Windows
C:WindowsSystem32drivers
这篇关于Java 中的 getPath()、getAbsolutePath() 和 getCanonicalPath() 之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!