
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get the Name of the Parent Directory in Java
In this program, we will demonstrate how to retrieve the parent directory of a file using the File class in Java. The name of the parent directory of the file or directory can be obtained using the method getParent() method using the java.io package. This method returns the parent directory path name string or null if there is no parent named.
Steps to get the name of the parent directory
Following are the steps to get the name of the parent directory ?
- We will start by importing the java.io.File class.
- Create a File object with the specified path and file name in Java.
- Print the full file path using System.out.println().
- Use the getParent() method to retrieve and print the parent directory of the file.
- Display the parent directory in the output.
Java program to get the name of the parent directory
Below is the Java program that demonstrates this is given as follows ?
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()); } }
Output
File: C:/jdk11.0.2/demo1.java Parent: C:/jdk11.0.2
Code Explanation
In the given program first, we will import the File class from the java.io package after that we will create a File object with the path "C:/jdk11.0.2/demo1.java". The System.out.println("File: " + file) prints the full file path. Then, file.getParent() is used to retrieve the parent directory, which is printed as "C:/jdk11.0.2". If no parent exists, getParent() would return null.