Get the name of the file and path in Java


The name of the file and the name of the path can be obtained using the methods java.io.File.getName() and java.io.File.getPath() respectively. The getName() returns the name of the file or the directory. The getPath() returns the abstract pathname in the form of a pathname string.

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("File name: " + file.getName());
      System.out.println("Path name: " + file.getPath());
   }
}

The output of the above program is as follows −

Output

File name: demo1.java
Path name: C:/jdk11.0.2/demo1.java

Now let us understand the above program.

The file name and path name of the file is printed using the methods getName() and getPath() respectively. A code snippet that demonstrates this is given as follows −

File demo1 = new File("C:" + File.separator + "jdk11.0.2" + File.separator, "demo1.java");
System.out.println("File name: " + demo1.getName());
System.out.println("Path name: " + demo1.getPath());

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements