Home »
Java programming language
Java File Class String getParent() method with Example
Java File Class String getParent() method: Here, we are going to learn about the String getParent() method of File class with its syntax and example.
Submitted by Preeti Jain, on July 10, 2019
File Class String getParent()
- This method is available in package java.io.File.getParent().
- This method is used to return the parent of the given file object(i.e In case of file object it returns the filepath where the file exists in the form of a string).
- The return type of this method is String (i.e It returns the parent of the file object and parent is in String form(i.e filepath is string where the file exists).
Syntax:
String getParent(){
}
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 String i.e. It returns the parent of the given file object if parent does not exist then it returns null as a string.
Java program to demonstrate example of getParent() 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 GetParent {
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 getParent() method returns a string which
// contain the parent of the given file object.
String file_parent1 = file1.getParent();
// By using getParent() method returns null as a string
// because there is no parent of the given file object.
String file_parent2 = file2.getParent();
// Display the parent of the given file object
System.out.println("The parent of the given file_parent1 is :" + file_parent1);
System.out.println("The parent of the given file_paren2 is :" + file_parent2);
} catch (Exception e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Output
D:\Programs>javac GetParent.java
D:\Programs>java GetParent
The parent of the given file_parent1 is :C:\Users\computer clinic\OneDrive\Articles
The parent of the given file_paren2 is :null