Java中的getPath(),getAbsolutePath()和getCanonicalPath()有什么区别?

本文翻译自:What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

What's the difference between getPath() , getAbsolutePath() , and getCanonicalPath() in Java? Java中的getPath()getAbsolutePath()getCanonicalPath()有什么getCanonicalPath()

And when do I use each one? 我什么时候使用每一个?


#1楼

参考:https://stackoom.com/question/4bye/Java中的getPath-getAbsolutePath-和getCanonicalPath-有什么区别


#2楼

In short: 简而言之:

  • getPath() gets the path string that the File object was constructed with, and it may be relative current directory. getPath()获取构造File对象的路径字符串,它可能是相对当前目录。
  • getAbsolutePath() gets the path string after resolving it against the current directory if it's relative, resulting in a fully qualified path. getAbsolutePath()获取路径字符串后解析当前目录(如果它是相对的),从而产生一个完全限定的路径。
  • 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. getCanonicalPath()在解析当前目录的任何相对路径后获取路径字符串,并删除任何相对路径( ... ),并删除任何文件系统链接以返回文件系统认为引用文件系统的规范方法的路径它指向的对象。

Also, each of these has a File equivalent which returns the corresponding File object. 此外,每个都有一个File等效项,返回相应的File对象。


#3楼

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. .\\file.txt - 这是一个路径。 It's neither an absolute path nor a canonical path. 它既不是绝对的道路,也不是规范的道路。

C:\\temp\\myapp\\bin\\..\\\\..\\file.txt - This is a path and an absolute path. C:\\temp\\myapp\\bin\\..\\\\..\\file.txt - 这是路径和绝对路径。 It's not a canonical path. 这不是一个规范的道路。

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 eg ./file.txt becomes c:/temp/file.txt ). 从路径转换为规范路径使其成为绝对路径(通常在当前工作目录上添加,例如./file.txt变为c:/temp/file.txt )。 The canonical path of a file just "purifies" the path, removing and resolving stuff like ..\\ and resolving symlinks (on unixes). 文件的规范路径只是“净化”路径,删除和解析像..\\和解析符号链接(在unixes上)之类的东西。

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

#4楼

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; 所以, getPath()为你提供了基于File对象的路径,它可能是也可能不是相对的; getAbsolutePath() gives you an absolute path to the file; getAbsolutePath()为您提供文件的绝对路径; and getCanonicalPath() gives you the unique absolute path to the file. getCanonicalPath()为您提供文件的唯一绝对路径。 Notice that there are a huge number of absolute paths that point to the same file, but only one canonical path. 请注意,存在大量指向同一文件的绝对路径,但只有一条规范路径。

When to use each? 什么时候使用? Depends on what you're trying to accomplish, but if you were trying to see if two Files are pointing at the same file on disk, you could compare their canonical paths. 取决于您要完成的任务,但如果您尝试查看两个Files是否指向磁盘上的同一文件,则可以比较它们的规范路径。 Just one example. 只是一个例子。


#5楼

The big thing to get your head around is that the File class tries to represent a view of what Sun like to call "hierarchical pathnames" (basically a path like c:/foo.txt or /usr/muggins ). 让你c:/foo.txt的重要一点是, File类试图表示Sun喜欢称之为“分层路径名”的视图(基本上是c:/foo.txt/usr/muggins类的路径)。 This is why you create files in terms of paths. 这就是您根据路径创建文件的原因。 The operations you are describing are all operations upon this "pathname". 您描述的操作是对此“路径名”的所有操作。

  • getPath() fetches the path that the File was created with ( ../foo.txt ) getPath()获取使用( ../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 ) getAbsolutePath()获取创建文件的路径,但如果路径是相对的,则包含有关当前目录的信息( /usr/bobstuff/../foo.txt
  • getCanonicalPath() attempts to fetch a unique representation of the absolute path to the file. getCanonicalPath() 尝试获取文件的绝对路径的唯一表示。 This eliminates indirection from ".." and "." 这消除了“..”和“。”的间接方向。 references ( /usr/foo.txt ). 引用( /usr/foo.txt )。

Note I say attempts - in forming a Canonical Path, the VM can throw an IOException . 注意我说尝试 - 在形成规范路径时,VM可以抛出IOException This usually occurs because it is performing some filesystem operations, any one of which could fail. 这通常是因为它正在执行某些文件系统操作,其中任何一个都可能失败。


#6楼

getPath() returns the path used to create the File object. getPath()返回用于创建File对象的路径。 This return value is not changed based on the location it is run (results below are for windows, separators are obviously different elsewhere) 此返回值不会根据其运行位置而更改(以下结果适用于Windows,分隔符在其他位置显然不同)

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. getAbsolutePath()将根据执行位置或驱动器解析路径。 So if run from c:\\test : 所以如果从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. getCanonicalPath()依赖于系统。 It will resolve the unique location the path represents. 它将解析路径所代表的唯一位置。 So if you have any "."s in the path they will typically be removed. 因此,如果路径中有任何“。”,则通常会将其删除。

As to when to use them. 至于何时使用它们。 It depends on what you are trying to achieve. 这取决于你想要达到的目标。 getPath() is useful for portability. getPath()对于可移植性很有用。 getAbsolutePath() is useful to find the file system location, and getCanonicalPath() is particularly useful to check if two files are the same. getAbsolutePath()对于查找文件系统位置很有用,而getCanonicalPath()对于检查两个文件是否相同特别有用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值