文档章节

Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java

Ciet
 Ciet
发布于 01/29 23:05
字数 729
阅读 181
收藏 0

1. Overview

The java.io.File class has three methods — getPath(), getAbsolutePath() and getCanonicalPath() — to obtain the filesystem path.

In this article, we'll have a quick look at the differences between them and discuss a use case where you may choose to use one over the others.

2. Method Definitions and Examples

Let's start by going over the definitions of the three methods, along with examples based on having the following directory structure present in the user's home directory:

|-- baeldung
     |-- baeldung.txt
     |-- foo
     |   |-- foo-one.txt
     |   \-- foo-two.txt
     \-- bar
         |-- bar-one.txt
         |-- bar-two.txt
         \-- baz
             |-- baz-one.txt
             \-- baz-two.txt

2.1. getPath()

Simply put, getPath() returns the String representation of the file's abstract pathname. This is essentially the pathname passed to the File constructor.

So, if the File object was created using a relative path, the returned value from getPath() method would also be a relative path.

If we invoke the following code from the {user.home}/baeldung directory:

1
2
File file = new File( "foo/foo-one.txt" );
String path = file.getPath();

The path variable would have the value:

1
2
foo/foo-one.txt  // on Unix systems
foo\foo-one.txt  // on Windows systems

Notice that for the Windows system, the name-separator character has changed from the forward slash(/) character, which was passed to the constructor, to the backslash (\) character. This is because the returned String always uses the platform's default name-separator character.

2.2. getAbsolutePath()

The getAbsolutePath() method returns the pathname of the file after resolving the path for the current user directory — this is called an absolute pathname. So, for our previous example, file.getAbsolutePath() would return:

1
2
/home/username/baeldung/foo/foo-one.txt     // on Unix systems
C:\Users\username\baeldung\foo\foo-one.txt  // on Windows systems

This method only resolves the current directory for a relative path. Shorthand representations (such as “.” and “..”) are not resolved further. Hence when we execute the following code from the directory {user.home}/baeldung:

1
2
File file = new File( "bar/baz/../bar-one.txt" );
String path = file.getAbsolutePath();

The value of the variable path would be:

1
2
/home/username/baeldung/bar/baz/../bar-one.txt      // on Unix systems
C:\Users\username\baeldung\bar\baz\..\bar-one.txt   // on Windows systems

2.3. getCanonicalPath()

The getCanonicalPath() method goes a step further and resolves the absolute pathname as well as the shorthands or redundant names like “.” and “.. as per the directory structure. It also resolves symbolic links on Unix systems and converts the drive letter to a standard case on Windows systems.

So for the previous example, getCanonicalPath() method would return:

1
2
/home/username/baeldung/bar/bar-one.txt     // on Unix systems
C:\Users\username\baeldung\bar\bar-one.txt  // on Windows systems

Let's take another example. Given current directory as ${user.home}/baeldung and File object created using the parameter new File(“bar/baz/./baz-one.txt”), the output for getCanonicalPath() would be:

1
2
/home/username/baeldung/bar/baz/baz-one.txt     // on Unix systems
C:\Users\username\baeldung\bar\baz\baz-one.txt  // on Windows Systems

It's worth mentioning that a single file on the filesystem can have an infinite number of absolute paths since there's an infinite number of ways shorthand representations can be used. However, the canonical path will always be unique since all such representations are resolved.

Unlike the last two methods, getCanonicalPath() may throw IOException because it requires filesystem queries.

For example, on Windows systems, if we create a File object with one of the illegal characters, resolving the canonical path will throw an IOException:

1
new File( "*" ).getCanonicalPath();

3. Use Case

Let's say we're writing a method that takes in a File object as a parameter and saves its fully qualified name into a database. We don't know whether the path is relative or contains shorthands. In this case, we may want to use getCanonicalPath().

However, since getCanonicalPath() reads the filesystem, it comes at a performance cost. If we are sure that there are no redundant names or symbolic links and drive letter case is standardized (if using a Windows OS), then we should prefer using getAbsoultePath().

4. Conclusion

In this quick tutorial, we covered the differences between the three File methods to get filesystem path. We have also shown a use case where one method may be preferred over the other.

A Junit test class demonstrating the examples of this article can be found over on GitHub.

本文转载自:https://www.baeldung.com/java-path

Ciet
粉丝 0
博文 68
码字总数 70
作品 0
南京
其他
私信 提问
加载中

评论(0)

getPath() getAbsolutePath() getCanonicalPath()不同之处

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......

Oscarfff
2016/04/26
53
0
File类的getPath、getAbsolutePath和getCanonicalPath的不同

一、概念上的不同 getPathpublic String getPath()将此抽象路径名转换为一个路径名字符串。所得字符串使用默认名称分隔符分隔名称序列中的名称。返回:此抽象路径名的字符串形式 ----------...

bliver
2014/03/12
4.1K
0
JVM GC 之「AdaptiveSizePolicy」实战

一、AdaptiveSizePolicy简介 AdaptiveSizePolicy(自适应大小策略) 是 JVM GC Ergonomics(自适应调节策略) 的一部分。 如果开启 AdaptiveSizePolicy,则每次 GC 后会重新计算 Eden、From 和 ...

onedotdot
2019/03/31
10
0
JNA调用DLL函数遇到的几个问题

最近一个JSP项目需要用到分词模块,而分词模块实用C++写成的DLL库。于是上网搜各种方法,最后选择了JNA作为JSP调用DLL的工具。 JNA(Java Native Access )提供一组Java工具类用于在运行期动...

雷霄骅
2013/09/30
203
0
盘符下查找文件数量不匹配 的问题

写了个查找指定文件下文件名带java(不区分大小写)四个字符的文件数量,在其他文件下查找的数量与用windows自带查找的数量一致,可是当查找e盘下所有的文件数量时比用java代码查找的数量少5...

Packer_Z
2017/05/10
73
2

没有更多内容

加载失败,请刷新页面

加载更多

Tomcat优化配置

启动tomcat,访问配置: http://localhost:8080/manager/status

小小小施爷
27分钟前
71
0
如何更改为旧版本的Node.js

我在Ubuntu 10.10上运行Node.js版本v0.5.9-pre 。 我想使用v0.5.0-pre版本。 如何回滚到旧版本的节点? #1楼 用于管理Node的多个版本的另一个好的库是N: https : //github.com/visionmedia...

技术盛宴
33分钟前
68
0
三极管工作原理

随着科学技的发展,电子技术的应用几乎渗透到了人们生产生活的方方面面。晶体三极管作为电子技术中一个最为基本的常用器件,其原理对于学习电子技术的人自然应该是一个重点。三极管原理的关键...

黑客画家
36分钟前
105
0
WordCounter for mac(字数统计器) v1.6.2

想要快速的完成mac电脑上的文档字数统计,字数统计器WordCounter mac版是您的首先,该软件可以查看您的写作统计,如字数,字数,句数,行数,段数等简单而强大,别犹豫了来macdown下载体验吧...

云不若
38分钟前
47
0
mybatis-generator-maven-plugin:Communications link failure

使用 mybatis-generator 的 maven 插件可能会报出如下问题 Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.7:generate (default-cli) on project MyProj......

恒宝乐园
38分钟前
69
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部