Get absolute file path in Java example

Get absolute file path example shows how to get the absolute path of 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?

Use getAbsolutePath method of Java File class to get the 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 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 path which 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

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *