Open In App

How to Get the File’s Parent Directory in Java?

Java is one of the most popular and powerful programming languages. It is widely used for various purposes. In this article, we are going to learn how to find the parent directory of a file or a specified path.

Methods to Get the Parent Directory of a file

In Java, we can get the parent Directory with the help of two methods.



Program to Get the File’s Parent Directory in Java

1. Using java.io.File and getParentFile()

In this method, we have a path stored in a string variable now we are creating a file object. After creating a file object, we call the getParentFile() method to get the parent directory of the file object.




// Java program to get the file's parent directory
// Using java.io.File and getParentFile()
import java.io.File;
public class lokesh {
     public static void main(String[] args) 
     {
        // specify the file path
        String filePath = "E:/Lokesh/Java/learn/JavaFile.java";
        System.out.println("Enter the file path: " +filePath);
  
        // create a File object
        File file = new File(filePath);
  
        // get the parent directory as a File object
        File parentDirectory = file.getParentFile();
  
        if (parentDirectory != null) {
            System.out.println("Parent Directory: " + parentDirectory);
        } else {
            System.out.println("The file does not have a parent directory.");
        }
     }
}

Output

Enter the file path: E:/Lokesh/Java/learn/JavaFile.java
Parent Directory: E:/Lokesh/Java/learn


Explanation of the above program:

2. java.nio.file.Path and getParent()

In this method, we are first declaring the path of file and the creating an object of the path and after creating an object, we are getting the parent of the file path.




// Java program to get the file's parent directory
// Using java.nio.file.Path and getParent()
import java.nio.file.Path;
import java.nio.file.Paths;
  
public class GetParentDirectoryExample 
{
    public static void main(String[] args)
    {
        // specify the file path
       String filePath = "E:/Lokesh/Java/learn/JavaFile.java";
       System.out.println("Enter the file path: " +filePath);
  
        // create a Path object
        Path path = Paths.get(filePath);
  
        // get the parent directory as a Path object
        Path parentDirectory = path.getParent();
  
        if (parentDirectory != null) {
            System.out.println(
                "Parent Directory: "
                + parentDirectory);
        }
        else {
            System.out.println("The file does not have a parent directory.");
        }
    }
}

Output
Enter the file path: E:/Lokesh/Java/learn/JavaFile.java
Parent Directory: E:/Lokesh/Java/learn


Explanation of the above program:


Article Tags :