How to get absolute File path in Java

How to get absolute File path in Java?

In this Example we are going to learn how to get absolute File path in Java

Example :

import java.io.File;
 
public class FileAbsolutePath {
 public static void main(String[] args) {
        String strFilePath = "text.txt";
        File file = new File(strFilePath);
        /*
         * Use getAbsolutePath method of the File class
         * to get file's absolute path in file system.
         */
        System.out.println( file.getAbsolutePath() );
    }
}

Output

D:\JAVA\JavaApplication1\text.txt 

 

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

getPath():  This method returns a path that was used to create a File object. 

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