Skip to Content

Get name of parent directory

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