gotchajavaCritical
What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?
Viewed 0 times
getabsolutepathjavagetpathandbetweenthedifferencewhatgetcanonicalpath
Problem
What's the difference between
And when do I use each one?
getPath(), getAbsolutePath(), and getCanonicalPath() in Java?And when do I use each one?
Solution
Consider these filenames:
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.
Also note the following example with nio.Paths:
While both paths refer to the same location, the output will be quite different:
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\driversCode Snippets
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());C:\Windows
C:\Windows\System32\driversContext
Stack Overflow Q#1099300, score: 682
Revisions (0)
No revisions yet.