643

What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

And when do I use each one?

1
  • 2
    Dont forget Path.toAbsolutePath().normalize() which is a good middle ground between canonical (real) path and absolute path alone.
    – eckes
    Jun 18, 2017 at 19:48

6 Answers 6

673

Consider these filenames:

C:\temp\file.txt - This is a path, an absolute path, and a canonical path.

.\file.txt - This is a path. It's neither an absolute path nor a canonical path.

C:\temp\myapp\bin\..\\..\file.txt - This is a path and an absolute path. 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 e.g. ./file.txt becomes c:/temp/file.txt). The canonical path of a file just "purifies" the path, removing and resolving stuff like ..\ and resolving symlinks (on unixes).

Also note the following example with 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
5
  • 11
    FWIW, it's not a given that C:\temp\file.txt is a canonical path - the temp directory might be a file system soft link or hard link (a junction in NTFS), and file.txt might be a soft link. I don't know if file systems can distinguish hard links to files. Oct 19, 2010 at 18:10
  • 1
    path does not really consider those issues or existence of any of the components, only the syntax of it.
    – escape-llc
    Sep 13, 2016 at 9:58
  • 1
    It does, canonical path (unlike normalized path) does hit the file system.
    – eckes
    Jun 18, 2017 at 19:44
  • 2
    Basically, I can't see a reason why one should use getAbsolutePath() instead of getCanonicalPath(). It even looks better because the canonical one automatically resolves those ../ parts.
    – Scadge
    Feb 15, 2018 at 13:01
  • 6
    Don't forget that getCanonicalPath throws an IOException while getAbsolutePath does not, if this is a consideration. Mar 27, 2018 at 6:49
140

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.

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. Just one example.

4
  • 7
    It's arguable that Java got it's implementation of an "absolute" path wrong; it really should've removed any relative path elements in an absolute path. The canonical form would then remove any FS links or junctions in the path. May 14, 2014 at 18:56
  • but if you were trying to see if two Files are pointing at the same file on disk How? example please? Apr 4, 2016 at 13:49
  • @UnKnown: You'd use the canonical path for that. Mar 25, 2018 at 21:15
  • Question... When would you ever want to use the absolute path over the canonical path? Doesn't checking the canonical path "work better" in more scenarios?
    – Collin
    Jan 23 at 16:28
87

In short:

  • getPath() gets the path string that the File object 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.

Also, each of these has a File equivalent which returns the corresponding File object.

Note that IMO, Java got the implementation of an "absolute" path wrong; it really should remove any relative path elements in an absolute path. The canonical form would then remove any FS links or junctions in the path.

1
  • 1
    Only explanation I found to be clear as ice. Thanks!
    – Dude156
    Oct 27, 2020 at 20:05
41

getPath() returns the path used to create the File object. This return value is not changed based on the location it is run (results below are for windows, separators are obviously different elsewhere)

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:

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.

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.

2
  • can you give me any example of this? getCanonicalPath() is particularly useful to check if two files are the same. Apr 4, 2016 at 13:50
  • So basically if you want your code to work on multiple operating systems you should just use getCanonicalPath() ??
    – Collin
    Jan 23 at 16:30
23

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). 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)
  • 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() attempts to fetch a unique representation of the absolute path to the file. This eliminates indirection from ".." and "." references (/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.

3

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.tmpdir System property returns, then this method will return the "full" filename.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.