- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to get the parent directory of a file in Java
Problem Description
How to get the parent directory of a file?
Solution
Following example shows how to get the parent directory of a file by the use of file.getParent() method of File class.
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("C:/File/demo.txt");
String strParentDirectory = file.getParent();
System.out.println("Parent directory is : " + strParentDirectory);
}
}
Result
The above code sample will produce the following result.
Parent directory is : File
The following is an another example to get the parent directory of a file
import java.io.File;
import java.util.Scanner;
public class CheckParentDirectory {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the file path");
String filePath = scanner.next();
File fileToTest = new File(filePath);
if (!fileToTest.isDirectory()) {
System.out.println("This is File");
System.out.println("Parent Folder of this file is :" + fileToTest.getParent());
} else {
System.out.println("This is Directory");
System.out.println(
"Parent Folder of this directory is :" + fileToTest.getParent());
}
}
}
The above code sample will produce the following result.
Enter the file path C:\Apache24\htdocs\javaexamples\dir_modification.htm This is File Parent Folder of this file is :C:\Apache24\htdocs\javaexamples
java_directories.htm
Advertisements