How to get the parent directory of a file in Java



Problem Description

How to get the parent directory of a file?

Solution

Following example shows how to get the parent directory of a file by the use of file.getParent() method of File class.

import java.io.File;

public class Main {
   public static void main(String[] args) { 
      File file = new File("C:/File/demo.txt");
      String strParentDirectory = file.getParent();
      System.out.println("Parent directory is : " + strParentDirectory);
   }
}

Result

The above code sample will produce the following result.

Parent directory is : File

The following is an another example to get the parent directory of a file

import java.io.File;
import java.util.Scanner;

public class CheckParentDirectory { 
   public static void main(String args[]) {
      Scanner scanner = new Scanner(System.in);
      System.out.println("Enter the file path");
      String filePath = scanner.next();
      File fileToTest = new File(filePath);
      
      if (!fileToTest.isDirectory()) {
         System.out.println("This is File");
         System.out.println("Parent Folder of this file is :" + fileToTest.getParent());
      } else {
         System.out.println("This is Directory");
         System.out.println(
            "Parent Folder of this directory is :" + fileToTest.getParent());
      } 
   }
}

The above code sample will produce the following result.

Enter the file path
C:\Apache24\htdocs\javaexamples\dir_modification.htm
This is File
Parent Folder of this file is :C:\Apache24\htdocs\javaexamples
java_directories.htm
Advertisements