Java获取文件的上级目录

通过 File 对象的 getParent 方法即可实现

// 通过 System.getProperty("user.dir") 方式获取到项目根目录
String projectRootDirectoryPath = System.getProperty("user.dir");
System.out.println("当前项目根目录为:\t" + projectRootDirectoryPath);
// 通过 File 对象的 getParent() 方法获取到根目录的上级目录
String parentPath = new File(projectRootDirectoryPath).getParent();
System.out.println("当前项目根目录的上级目录为:\t" + parentPath);

效果截图


Java中如何获取文件的上级目录

获取文件的父目录名称和父目录绝对地址

获取文件的父目录名称

import java.io.File;
 
public class Main {
    public static void main(String[] args) {
        //创建file对象
        File file = new File("C:/File/demo.txt");
        //先获取file的父文件,再getName
        String strParentDirectory = file.getParentFile().getName();
        System.out.println("文件的上级目录为 : " + strParentDirectory);
    }
}

输出结果:
File

获取文件的父目录绝对地址

import java.io.File;
 
public class Main {
    public static void main(String[] args) {
        //创建file对象
        File file = new File("C:/File/demo.txt");
        //先获取file的父文件,再getName
        String strParentDirectory = file.getParentFile().getName();
        System.out.println("文件的上级目录为 : " + strParentDirectory);
    }
}

输出结果:
C:/File

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文地址:https://blog.csdn.net/qq_43647359/article/details/108796311

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-28
猜你喜欢
  • 2022-12-23
  • 2021-11-19
  • 2022-12-23
  • 2022-12-23
  • 1970-01-01
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案