Skip to Content

Get name of specified file or directory

  1. /*
  2.   Get name of specified file or directory
  3.   This Java example shows how to get a name of specified file or directory denoted
  4.   by a path using getName method of Java File class.
  5. */
  6.  
  7. import java.io.*;
  8.  
  9. public class GetNameOfFileOrDirectory {
  10.  
  11.   public static void main(String[] args) {
  12.    
  13.     //create file object
  14.     File file = new File("C://FileIO//FileDemo.txt");
  15.    
  16.     /*
  17.      * To get a name of file or directory denoted by a path, use
  18.      * String getName() method of Java File class.
  19.      *
  20.      * This method returns name of the file or directory denoted by path.
  21.      */
  22.    
  23.      String strFileName = file.getName();
  24.    
  25.      System.out.println("File name is : " + strFileName);
  26.    
  27.   }
  28. }
  29.  
  30. /*
  31. Output would be
  32. File name is : FileDemo.txt
  33. */