如何获取文件的父目录?(How to get the parent directory of a file?)

优质
小牛编辑
129浏览
2023-12-01

问题描述 (Problem Description)

如何获取文件的父目录?

解决方案 (Solution)

下面的示例演示如何通过使用File类的file.getParent()方法获取文件的父目录。

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)

上面的代码示例将产生以下结果。

Parent directory is : 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());
      } 
   }
}

上面的代码示例将产生以下结果。

Enter the file path
C:\Apache24\htdocs\javaexamples\dir_modification.htm
This is File
Parent Folder of this file is :C:\Apache24\htdocs\javaexamples