Getting the Parents of file name path in Java

In this section, you will learn how to get the parent directory of the current working directory.

Getting the Parents of file name path in Java

In this section, you will learn how to get the parent directory of the current working directory.

 Getting the Parents of file name path in Java

Getting the Parents of file name path in Java

     

Introduction

In this section, you will learn how to get the parent directory of the current working directory.

Program uses getParent() method of the File class object to find the parent directory name of the current directory. 

getParent():
Above code returns the parent directory of the file/directory.

System.getProperty("user.dir"):
This method returns the user's current directory. The getProperty() method is the system method which is imported from the System class of the java.lang.*; package. This method tells about the system property according to the indicating argument. Here, the indicating argument user.dir indicates about the current directory.

Here is the code of the program : 

import java.io.*;

public class  GetParentDir{
  private static void dirlist(String fname){
  File dir = new File(fname);
  String parentpath = dir.getParent();
  System.out.println("Current Directory : "+ dir);
  System.out.println("parent Directory : "+ parentpath);
  }

  public static void main(String[] args){
  String currentdir = System.getProperty("user.dir");
  dirlist(currentdir);
  }
}

Download this example.