Java Program to get the name of the parent directory of the file or directory

Java 8Object Oriented ProgrammingProgramming

The name of the parent directory of the file or directory can be obtained using the method java.io.File.getParent(). This method returns the parent directory path name string or null if there is no parent named.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.io.File;
public class Demo {
   public static void main(String[] args) {
      File file = new File("C:" + File.separator + "jdk11.0.2" + File.separator, "demo1.java");
      System.out.println("File: " + file);
      System.out.println("Parent: " + file.getParent());
   }
}

The output of the above program is as follows −

Output

File: C:/jdk11.0.2/demo1.java
Parent: C:/jdk11.0.2

Now let us understand the above program.

The getParent() method is used to print the name of the parent directory of the file. Also, the file is printed. A code snippet that demonstrates this is given as follows −

File file = new File("C:" + File.separator + "jdk11.0.2" + File.separator, "demo1.java");
System.out.println("File: " + file);
System.out.println("Parent: " + file.getParent());
raja
Published on 25-Feb-2019 11:50:44
Advertisements