Java 示例 - 父目录

  • 问题描述

    如何获取文件的父目录?
  • 解决方案

    下面的例子展示了如何使用 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);
       }
    }
    
  • 结果

    上面的代码示例将产生以下结果。
    
    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