Java中的getPath()
、getAbsolutePath()
、getCanonicalPath()
有什么区别?
我什么时候使用它们?
最佳答案
考虑这些文件名:
C:\temp\file.txt
- 这是路径、绝对路径和规范路径。
.\file.txt
- 这是一个路径。它既不是绝对路径也不是规范路径。
C:\temp\myapp\bin\..\\..\file.txt
- 这是一个路径和一个绝对路径。这不是规范路径。
规范路径始终是绝对路径。
从路径转换为规范路径使其成为绝对路径(通常附加在当前工作目录上,例如 ./file.txt
变为 c:/temp/file.txt
)。文件的规范路径只是“净化”路径,删除和解析 ..\
之类的内容并解析符号链接(symbolic link)(在 unix 上)。
还要注意以下带有 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());
虽然两条路径都指向同一个位置,但输出会完全不同:
C:\Windows
C:\Windows\System32\drivers
关于java - Java 中的 getPath()、getAbsolutePath() 和 getCanonicalPath() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1099300/