Java file get parent directory


 

Java file get parent directory

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

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

Java file get parent directory

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

Description of code:

The package java.io.* package works with both files and directories. File object represents both file and directories. You can see in the given example we have created a File object and parse the file. Then through its object, we have called getParent() method which of String type. This method returns the parent directory of specified file.

Here is the code:

import java.io.*;

public class GetParentDirectory {
	public static void main(String[] args) {
		File file = new File("C://Answers/File/out.txt");
		String parent = file.getParent();
		System.out.println("Parent directory is : " + parent);
	}
}

Through the method getParent(), you can find the parent directory of any file.

Output:

Parent directory is : C:\Answers\File

Ads