Skip to Content

Get parent directory as a File object

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

Advertisement: