Java 中的 getPath()、getAbsolutePath() 和 getCanonicalPath() 之间有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1099300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?
提问by knt
What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath()in Java?
什么之间的区别getPath(),getAbsolutePath()以及getCanonicalPath()在Java中?
And when do I use each one?
我什么时候使用每一个?
采纳答案by nos
Consider these filenames:
考虑这些文件名:
C:\temp\file.txt- This is a path, an absolute path, and a canonical path.
C:\temp\file.txt- 这是一条路径、一条绝对路径和一条规范路径。
.\file.txt- This is a path. It's neither an absolute path nor a canonical path.
.\file.txt——这是一条路。它既不是绝对路径,也不是规范路径。
C:\temp\myapp\bin\..\\..\file.txt- This is a path and an absolute path. It's not a canonical path.
C:\temp\myapp\bin\..\\..\file.txt- 这是一个路径和一个绝对路径。这不是规范路径。
A canonical path is always an absolute path.
规范路径始终是绝对路径。
Converting from a path to a canonical path makes it absolute (usually tack on the current working directory so e.g. ./file.txtbecomes c:/temp/file.txt). The canonical path of a file just "purifies" the path, removing and resolving stuff like ..\and resolving symlinks (on unixes).
从路径转换为规范路径使其成为绝对路径(通常附加在当前工作目录上,例如./file.txt变为c:/temp/file.txt)。文件的规范路径只是“净化”路径,删除和解析诸如..\和解析符号链接之类的东西(在 unix 上)。
Also note the following example with nio.Paths:
另请注意以下带有 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:\Windows\System32\drivers
回答by Lawrence Dol
In short:
简而言之:
getPath()gets the path string that theFileobject was constructed with, and it may be relative current directory.getAbsolutePath()gets the path string after resolving it against the current directory if it's relative, resulting in a fully qualified path.getCanonicalPath()gets the path string after resolving any relative path against current directory, and removes any relative pathing (.and..), and any file system links to return a path which the file system considers the canonical means to reference the file system object to which it points.
getPath()获取File构造对象的路径字符串,它可能是相对当前目录。getAbsolutePath()如果它是相对的,则在针对当前目录解析后获取路径字符串,从而产生完全限定的路径。getCanonicalPath()在针对当前目录解析任何相对路径后获取路径字符串,并删除任何相对路径(.和..)以及任何文件系统链接以返回路径,文件系统认为该路径是引用它指向的文件系统对象的规范方法。
Also, each of these has a File equivalent which returns the corresponding Fileobject.
此外,这些中的每一个都有一个 File 等效项,它返回相应的File对象。
回答by dave4351
The best way I have found to get a feel for things like this is to try them out:
我发现对此类事情有一种感觉的最好方法是尝试它们:
import java.io.File;
public class PathTesting {
public static void main(String [] args) {
File f = new File("test/.././file.txt");
System.out.println(f.getPath());
System.out.println(f.getAbsolutePath());
try {
System.out.println(f.getCanonicalPath());
}
catch(Exception e) {}
}
}
Your output will be something like:
您的输出将类似于:
test\..\.\file.txt
C:\projects\sandbox\trunk\test\..\.\file.txt
C:\projects\sandbox\trunk\file.txt
So, getPath()gives you the path based on the File object, which may or may not be relative; getAbsolutePath()gives you an absolute path to the file; and getCanonicalPath()gives you the unique absolute path to the file. Notice that there are a huge number of absolute paths that point to the same file, but only one canonical path.
因此,getPath()为您提供基于 File 对象的路径,该路径可能是也可能不是相对的;getAbsolutePath()为您提供文件的绝对路径;并getCanonicalPath()为您提供文件的唯一绝对路径。请注意,有大量绝对路径指向同一个文件,但只有一个规范路径。
When to use each? Depends on what you're trying to accomplish, but if you were trying to see if two Filesare pointing at the same file on disk, you could compare their canonical paths. Just one example.
什么时候使用?取决于您要完成的任务,但如果您要查看两个Files文件是否指向磁盘上的同一个文件,则可以比较它们的规范路径。只是一个例子。
回答by butterchicken
The big thing to get your head around is that the Fileclass tries to represent a view of what Sun like to call "hierarchical pathnames" (basically a path like c:/foo.txtor /usr/muggins). This is why you create files in terms of paths. The operations you are describing are all operations upon this "pathname".
让您大开眼界的是,File该类试图表示 Sun 喜欢称之为“分层路径名”(基本上是类似c:/foo.txtor的路径/usr/muggins)的视图。这就是您根据路径创建文件的原因。您所描述的操作都是对这个“路径名”的操作。
getPath()fetches the path that the File was created with (../foo.txt)getAbsolutePath()fetches the path that the File was created with, but includes information about the current directory if the path is relative (/usr/bobstuff/../foo.txt)getCanonicalPath()attemptsto fetch a unique representation of the absolute path to the file. This eliminates indirection from ".." and "." references (/usr/foo.txt).
getPath()获取使用 (../foo.txt)创建文件的路径getAbsolutePath()获取创建 File 的路径,但如果路径是相对的,则包含有关当前目录的信息 (/usr/bobstuff/../foo.txt)getCanonicalPath()尝试获取文件绝对路径的唯一表示。这消除了“..”和“.”的间接性。参考文献(/usr/foo.txt)。
Note I say attempts- in forming a Canonical Path, the VM can throw an IOException. This usually occurs because it is performing some filesystem operations, any one of which could fail.
注意我说的是尝试- 在形成规范路径时,VM 可以抛出一个IOException. 这通常是因为它正在执行一些文件系统操作,其中任何一个操作都可能失败。
回答by Rich Seller
getPath()returns the path used to create the Fileobject. This return value is not changed based on the location it is run (results below are for windows, separators are obviously different elsewhere)
getPath()返回用于创建File对象的路径。这个返回值不会根据它运行的位置而改变(下面的结果是针对窗口的,其他地方的分隔符明显不同)
File f1 = new File("/some/path");
String path = f1.getPath(); // will return "\some\path"
File dir = new File("/basedir");
File f2 = new File(dir, "/some/path");
path = f2.getPath(); // will return "\basedir\some\path"
File f3 = new File("./some/path");
path = f3.getPath(); // will return ".\some\path"
getAbsolutePath()will resolve the path based on the execution location or drive. So if run from c:\test:
getAbsolutePath()将根据执行位置或驱动器解析路径。所以如果从c:\test:
path = f1.getAbsolutePath(); // will return "c:\some\path"
path = f2.getAbsolutePath(); // will return "c:\basedir\some\path"
path = f3.getAbsolutePath(); // will return "c:\test\.\basedir\some\path"
getCanonicalPath()is system dependent. It will resolve the unique location the path represents. So if you have any "."s in the path they will typically be removed.
getCanonicalPath()是系统依赖的。它将解析路径代表的唯一位置。因此,如果路径中有任何“.”,它们通常会被删除。
As to when to use them. It depends on what you are trying to achieve. getPath()is useful for portability. getAbsolutePath()is useful to find the file system location, and getCanonicalPath()is particularly useful to check if two files are the same.
至于何时使用它们。这取决于您要实现的目标。getPath()便于携带。getAbsolutePath()对于查找文件系统位置getCanonicalPath()很有用,对于检查两个文件是否相同特别有用。
回答by Matthew Wise
I find I rarely have need to use getCanonicalPath()but, if given a File with a filename that is in DOS 8.3 format on Windows, such as the java.io.tmpdirSystem property returns, then this method will return the "full" filename.
我发现我很少需要使用getCanonicalPath()但是,如果在 Windows 上给定一个文件名是 DOS 8.3 格式的文件,例如java.io.tmpdirSystem 属性返回,那么此方法将返回“完整”文件名。

