温馨提示×

java怎么获取相对路径

小亿
104
2024-01-19 19:42:00
栏目: 编程语言

Java中获取相对路径的方法有多种。以下是其中一种常见的方法:

  1. 使用System.getProperty("user.dir")方法获取当前工作目录(即项目的根目录)的绝对路径。
String currentPath = System.getProperty("user.dir");
  1. 根据当前工作目录和相对路径构建文件对象。
String relativePath = "src/main/resources/file.txt";
String currentPath = System.getProperty("user.dir");
String absolutePath = currentPath + File.separator + relativePath;
File file = new File(absolutePath);

请注意,以上方法中的File.separator是系统相关的文件分隔符(在Windows上是\,在Linux上是/)。

0