Skip to content

Get absolute file path in Java example

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

How to get the absolute file path in Java?

We can use the getAbsolutePath method of Java File class to get the absolute file path.

This method returns the absolute path of the file as a  string.

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 a string containing the path information of the file, but they differ from one another.

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

getAbsolutePath(): This method returns a path that is a 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, the 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, the 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.

This example is a part of the Java File tutorial with examples.

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

About the author

Leave a Reply

Your email address will not be published.