示例 1: 获取当前工作目录
public class CurrDirectory { public static void main(String[] args) { String path = System.getProperty("user.dir"); System.out.println("Working Directory = " + path); } }
输出
Working Directory = C:\Users\Admin\Desktop\currDir
在上面的程序中,我们使用了
System
的
getProperty()
方法来获取程序的
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("Working Directory = " + path); } }
输出
Working Directory = C:\Users\Admin\Desktop\currDir
在上面的程序中,我们使用了
Path
的
get()
方法来获取我们程序的当前路径。这将返回工作目录的相对路径。
然后我们使用
toAbsolutePath()
将相对路径更改为绝对路径。由于它返回一个
Path
对象,我们需要使用
toString()
方法将其更改为字符串。