A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/javaexamples/dir_parent.htm below:

How to get the parent directory of a file in Java

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


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4