The difference is that there is only one canonical path to a file[1], while there can be many absolute paths to a file (depending on the system). For instance, on a Unix system, /usr/local/../bin
is the same as /usr/bin
. getCanonicalPath()
resolves those ambiguities and returns the (unique) canonical path. So if the current directory was /usr/local
, then:
File file = new File("../bin");
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
System.out.println(file.getCanonicalPath());
would print:
../bin
/usr/local/../bin
/usr/bin
Per Voo's suggestion: on Unix systems, getCanonicalPath()
will also resolve symbolic links if the symbolic link exists. Hard links are treated like normal files (which is basically what they are). Note, however, that a file need not exist for these methods to succeed.
[1] Well, not quite. As @Tom Hale points out in a comment, if the file system supports hard linked directories, there may be multiple canonical paths to a given file.