跳到主要内容

Java 程序:获取当前工作目录

要理解此示例,你应该具备以下 Java 编程主题的知识:

示例 1:获取当前工作目录

public class CurrDirectory {

public static void main(String[] args) {

String path = System.getProperty("user.dir");

System.out.println("工作目录 = " + path);

}
}

输出

工作目录 = C:\Users\Admin\Desktop\currDir

在上述程序中,我们使用了 SystemgetProperty() 方法来获取程序的 user.dir 属性。这将返回包含我们 Java 项目的目录。

示例 2:使用 Path 获取当前工作目录

import java.nio.file.Paths;

public class CurrDirectory {

public static void main(String[] args) {

String path = Paths.get("").toAbsolutePath().toString();
System.out.println("工作目录 = " + path);

}
}

输出

工作目录 = C:\Users\Admin\Desktop\currDir

在上述程序中,我们使用了 Pathget() 方法来获取我们程序的当前路径。这将返回一个相对于工作目录的相对路径。

然后我们使用 toAbsolutePath() 将相对路径转换为绝对路径。由于它返回一个 Path 对象,我们需要使用 toString() 方法将其转换为字符串。