Home »
Java programming language
Java File Class File getParentFile() method with Example
Java File Class File getParentFile() method: Here, we are going to learn about the File getParentFile() method of File class with its syntax and example.
Submitted by Preeti Jain, on July 10, 2019
File Class File getParentFile()
- This method is available in package java.io.File.getParentFile().
- This method is used to return the parent file of the given file object.
- The return type of this method is File (i.e It returns the parent file of the given file object and parent file is in File form.
Syntax:
File getParentFile(){
}
Parameter(s):
We don't pass any object as a parameter in the method of the File.
Return value:
The return type of this method is File i.e. It returns the parent file of the given file object if parent file does not exist then it returns null as a string.
Java program to demonstrate example of getParentFile() method
// import the File class because we will use File class methods
import java.io.*;
// import the Exception class because it may raise an
// exception when working with files
import java.lang.Exception;
public class GetParentFile {
public static void main(String[] args) {
try {
// Specify the path of file and we use double slashes to
// escape '\' character sequence for windows otherwise
// it will be considerable as url.
File file1 = new File("C:\\Users\\computer clinic\\OneDrive\\Articles\\ myjava.txt");
File file2 = new File("myjava.txt");
// By using getParentFile() method returns a File which
// contain the parent file of the given file object.
File parent_file1 = file1.getParentFile();
// By using getParentFile() method returns null as a string
// because there is no parent file of the given file object.
File parent_file2 = file2.getParentFile();
// Display the parent of the given file object
System.out.println("The parent of the given parent_file1 is :" + parent_file1);
System.out.println("The parent of the given parent_file2 is :" + parent_file2);
} catch (Exception e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Output
D:\Programs>javac GetParentFile.java
D:\Programs>java GetParentFile
The parent of the given parent_file1 is :C:\Users\computer clinic\OneDrive\Articles
The parent of the given parent_file2 is :null