Get Absolute path of a file in Java


The method java.io.File.getAbsolutePath() is used to obtain the absolute path of a file in the form of a string. This method requires no parameters.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.io.File;
public class Demo {
   public static void main(String[] args) {
      File file = new File("C:" + File.separator + "jdk11.0.2" + File.separator, "demo1.java");
      System.out.println("The absolute path name is: " + file.getAbsolutePath());
   }
}

The output of the above program is as follows −

Output

The absolute path name is:/C:/jdk11.0.2/demo1.java

Now let us understand the above program.

The absolute pathname of the file is obtained using the method java.io.File.getAbsolutePath() in the form of a string and is printed. A code snippet that demonstrates this is given as follows −

File file = new File("C:" + File.separator + "jdk11.0.2" + File.separator, "demo1.java");
System.out.println("The absolute path name is: " + file.getAbsolutePath());

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements