Posted By: Anonymous
What’s the difference between
getCanonicalPath() in Java?
And when do I use each one?
Consider these filenames:
C:tempfile.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:tempmyappbin..\..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.
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: