我想使用Java访问我的当前工作目录。

我的代码:

 String currentPath = new java.io.File(".").getCanonicalPath();
 System.out.println("Current dir:" + currentPath);

 String currentDir = System.getProperty("user.dir");
 System.out.println("Current dir using System:" + currentDir);

输出:

Current dir: C:\WINDOWS\system32
Current dir using System: C:\WINDOWS\system32

我的输出不正确,因为C驱动器不是我的当前目录。

如何获取当前目录?


当前回答

是什么让你认为c:\windows\system32不是你的当前目录?用户。dir属性显式为“用户的当前工作目录”。

换句话说,除非你从命令行启动Java,否则c:\windows\system32可能就是你的CWD。也就是说,如果您双击启动程序,CWD不太可能是您双击的目录。

编辑:这似乎只适用于旧的windows和/或Java版本。

其他回答

对于Java 11,你还可以使用:

var path = Path.of(".").toRealPath();

参见:路径操作(Java™教程>基本类>基本I/O)。

使用java.nio.file. path和java.nio.file。路径,您可以执行以下操作来显示Java认为的当前路径。这是7和以上,使用NIO。

Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current absolute path is: " + s);

这个输出:

Current absolute path is: /Users/george/NetBeansProjects/Tutorials

对我来说,这就是我上课的地方。

以相对方式构造路径(不使用前分隔符来表示正在构造绝对路径)将使用这个相对路径作为起点。

我希望你想访问当前目录,包括包,即,如果你的Java程序在c:\myApp\com\foo\src\service\MyTest.java,你想打印直到c:\myApp\com\foo\src\service,那么你可以尝试以下代码:

String myCurrentDir = System.getProperty("user.dir")
            + File.separator
            + System.getProperty("sun.java.command")
                    .substring(0, System.getProperty("sun.java.command").lastIndexOf("."))
                    .replace(".", File.separator);
    System.out.println(myCurrentDir);

注意:此代码仅在Windows和Oracle JRE中测试。

在Linux上,当你从终端运行一个jar文件时,这两个都会返回相同的字符串:"/home/CurrentUser",不管你的jar文件在哪里。这取决于启动jar文件时,您在终端上使用的当前目录。

Paths.get("").toAbsolutePath().toString();

System.getProperty("user.dir");

如果你的main类被称为MainClass,那么试试:

MainClass.class.getProtectionDomain().getCodeSource().getLocation().getFile();

这将返回一个包含jar文件绝对路径的String。

使用CodeSource # getLocation()。

这在JAR文件中也可以很好地工作。您可以通过ProtectionDomain#getCodeSource()获取CodeSource,而ProtectionDomain则可以通过Class#getProtectionDomain()获取。

public class Test {
    public static void main(String... args) throws Exception {
        URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();
        System.out.println(location.getFile());
    }
}