Possible Duplicate:
What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?
Any difference between those two?
canonicalpath and absolutepath?
If having difference, a real world example will be needed.
The canonical path is always an absolute and unique path. If String pathname is used to create a file object, it simply returns the pathname. This method first converts this pathname to absolute form if needed. To do that it will invoke the getAbsolutePath() Method and then maps it to its unique form.
Absolute path defines a path from the root of the file system e.g. C:\\ or D:\\ in Windows and from / in UNIX based operating systems e.g. Linux or Solaris. The canonical path is a little bit tricky because all canonical path is absolute, but vice-versa is not true.
getPath(): The getPath() method is a part of File class. This function returns the path of the given file object. The function returns a string object which contains the path of the given file object. getAbsolutePath(): The getAbsolutePath() returns a path object representing the absolute path of given 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With