What’s the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?
And when do I use each one?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.txtbecomesc:/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:
While both paths refer to the same location, the output will be quite different: