Java - Difference between getPath(), getAbsolutePath() and getCanonicalPath()

By xngo on February 21, 2019

Java provides different ways to get the path of a file. From the documentation, they are:

  • getPath(): It returns the pathname string repesenting the abstract pathname.
  • getAbsolutePath(): It returns the full path name but without resolving the shorthand representation of directories(e.g "." and "..").
  • getCanonicalPath(): It returns the full path name and resolve the shorthand representation of directories(i.e "." and "..").

Let me further explain using some examples of path.

  • .\file.txt: This is a path. But, it is neither an absolute path nor a canonical path.
  • C:\temp\myapp\bin\\..\\..\file.txt: This is a path and is also an absolute path. But it is not a canonical path because shorthand representation of directories is not resolved.
  • C:\temp\file.txt: This is a path, an absolute path, and a canonical path.

It is recommended to use canonical path. It will cause less problem in the long run. However, to get the canonical path, you have to read from the filesystem. Therefore, causing a performance hit.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.