本文翻译自: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可以抛出IOExceptionThis 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()对于检查两个文件是否相同特别有用。

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

  1. Java中,一切皆是对象——java中的对象类型与基本数据类型的区别

    起因:取一个list给另一个list赋值,然后在另一个list中取出进行修改.list其中类型为对象时,String时,基本数据类型时. [java中的对象类型与基本数据类型的区别] #声明和实例化 ...

  2. java堆和栈 常量池_GitHub - han-guang-xue/difference-of-stack-heap-pool: Java中堆、栈和常量池的区别...

    Java中堆.栈和常量池的区别 栈 堆 常量池的概念 首先我们先了解一下概念,Java把内存分成两种,一种叫做栈内存,一种叫做堆内存. 栈内存 存放基本类型的变量数据和对象类型的引用(请注意存放的是引 ...

  3. Java中Array和ArrayList之间的9个区别

    array和ArrayList都是Java中两个重要的数据结构,在Java程序中经常使用. 即使ArrayList在内部由数组支持,了解Java中的数组和ArrayList之间的差异对于成为一名优秀的 ...

  4. java中的NIO和IO到底是什么区别?20个问题告诉你答案

    摘要:NIO即New IO,这个库是在JDK1.4中才引入的.NIO和IO有相同的作用和目的,但实现方式不同,NIO主要用到的是块,所以NIO的效率要比IO高很多. 本文分享自华为云社区<jav ...

  5. java中list,set,map集合的区别,及面试要点

    Map集合:链接: Map集合的五种遍历方式及Treemap方法 Set集合:链接: Java中遍历Set集合的三种方法 TreeSet集合:链接: Java深入了解TreeSet,和迭代器遍历方法 ...

  6. java中*和**的作用 以及 /和/*和/**的区别

    一.java中*和**的作用 "*"就表示了所有的文件,但是"*"并不包括子目录下的文件: "**"匹配包含任意级子目录中所有的文件: 二. ...

  7. 解析java中方法的重载和重写之间的区别与联系

    解析java中方法的重载和重写之间的区别与联系 1 不同点 1.1 方法重写是在不同的类中(父子类),方法重载是在同一类中 1.2 方法重载最初的目的是构造方法的多样化,方法重写的目的是让重写的方法满 ...

  8. file的getPath getAbsolutePath和getCanonicalPath的不同

    file的这几个取得path的方法各有不同,下边说说详细的区别 概念上的区别:(内容来自jdk,个人感觉这个描述信息,只能让明白的人明白,不明白的人看起来还是有点难度(特别试中文版,英文版稍好些)所以 ...

  9. java final 变量 回收_java入门教程-Java中final,finally,finalize三个关键字的区别

    final 当这个关键字修饰一个类时,意味着他不能派生出新的子类,也就是说不能被继承,因此一个类不能被同时声明为abstract和final.当final修饰变量或者方法时,可以保证他们在使用中不会被 ...

最新文章

  1. python键_在Python中创建键命令
  2. 因特网的域名服务器系统的好处,dns域名服务器的作用是什么
  3. getGeneratedKeys自动获取主键的方法
  4. SQL中变量的赋值-select
  5. Swift3.0语言教程获取字符串编码与哈希地址
  6. SQL Server中Rollup关键字使用技巧
  7. C语言实现miniShell
  8. 解决:java.lang.IllegalStateException: ApplicationEventMulticaster not initialized
  9. 大数据上云第一课:MaxCompute授权和外表操作躲坑指南
  10. 小微型库(1.获取元素的API)
  11. 简单的企业网站后台的实现之流程
  12. CTO专访:坚守还是追新,开发者如何应对新技术暗潮
  13. 基于python的随机森林回归实现_python实现随机森林
  14. 企业私有云技术设计方案
  15. Xilinx Srio详解IP核使用
  16. 企业开展自媒体推广,重点是什么?
  17. 音视频入门系列-字幕篇(SSA ASS)
  18. 安卓手机管理器_手机QQ聊天记录如何导出到电脑上查看并打印
  19. 酒店:二维码如何应用于酒店管理
  20. 利用重复性渐变编写邮件线

热门文章

  1. 算法---------数组-----------寻找峰值
  2. 走进STM32世界之Hex程序烧写
  3. Build gradle : Could not find method packagingOptions() for arguments root Project “fasterDev”
  4. Mysql数据库事务详解
  5. css 中文字旋转,css
  6. php insert into values 可以是数组吗,PHP INSERT INTO插入不了数据有关问题
  7. java nio使用_什么时候使用NIO?
  8. Android Framework学习总结
  9. 极光推送收不到推送消息
  10. kettle分批处理大表数据_kettle-批量同步表数据