Java Program to get name of specified file or directory


The name of the specified file or directory can be obtained using the method java.io.File.getName(). The getName() returns the name of the file or the directory and it 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 + "JavaProgram" + File.separator, "demo1.txt");
      System.out.println("File name: " + file.getName());
   }
}

The output of the above program is as follows −

Output

File name: demo1.txt

Now let us understand the above program.

The name of the specified file is obtained using the method java.io.File.getName() and then printed. A code snippet that demonstrates this is given as follows −

File file = new File("C:" + File.separator + "JavaProgram" + File.separator, "demo1.txt");
System.out.println("File name: " + file.getName());

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

221 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements