Java IO

Get absolute file path in Java example

Get absolute file path example shows how to get absolute path of file in Java. Example also shows difference between path, absolute path and canonical path.

How to get absolute file path in Java?

Use getAbsolutePath method of Java File class to get absolute file path.

This method returns absolute path string of file.

Java file absolute path example

Output

As you can see from the output, I created the file without specifying the complete path but I when printed the absolute path, it gave the complete path of the file in the file system.

What is the difference between path, absolute path and canonical path?

Java File class provides three methods namely getPath, getAbsolutePath and getCanonicalPath. All three methods return String containing the path information of the file, but they differ with one another.

getPath():  This method returns path which was used to create File object. In short, it is the path using which the File object was first created.

getAbsolutePath(): This method returns path which is fully qualified path (after resolving the path relative to the current directory, if the relative path was used while creating the File object).

getCanonicaPath(): This method returns the path which is similar to the absolute path but it also converts . (Current directory) and .. (Parent directory) to the actual directories. It also resolves any symbolic links before returning the canonical path.

There can be only one canonical path but there could be many absolute paths for the same file. Sounds confusing? Let’s see an example.

Above given all paths are absolute paths for the same file one.txt. However, in this case, canonical path would be c:\one.txt.

Example:

Output

Note: My current working directory is C:\JavaCodeExamples\workspace\JavaCodeExamples. Your output will be different according to your current working directory.

Also note that, getPath, getAbsolutePath and getCanonicalPath methods return systems file path separator. I am using windows, so it returned path separated by \ even though I created file object using / or // file separators.

Please let us know your views in the comments section below.

Tags
Join 1000+ fellow learners! Enter your email address below: