Skip to content

Latest commit

 

History

History
56 lines (34 loc) · 1.49 KB

File metadata and controls

56 lines (34 loc) · 1.49 KB

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

原文: https://www.programiz.com/java-programming/examples/current-working-directory

在此程序中,您将学习获取 Java 中的当前工作目录。

示例 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

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


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

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

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

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