我想使用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驱动器不是我的当前目录。

如何获取当前目录?


当前回答

Java 11及更新版本

这个解决方案比其他解决方案更好,更可移植:

Path cwd = Path.of("").toAbsolutePath();

甚至

String cwd = Path.of("").toAbsolutePath().toString();

其他回答

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

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

System.getProperty("user.dir");

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

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

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

我在Linux上,这两种方法得到了相同的结果:

@Test
public void aaa()
{
    System.err.println(Paths.get("").toAbsolutePath().toString());

    System.err.println(System.getProperty("user.dir"));
}

Paths.get(" ")文档

System.getProperty(“user.dir”)文档

我希望你想访问当前目录,包括包,即,如果你的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中测试。

System.getProperty(“java.class.path”)

这并不是确切的要求,但这里有一个重要的注意:当在Windows机器上运行Java时,Oracle安装程序将“Java .exe”放入C:\Windows\system32中,这是Java应用程序的启动器(除非在PATH前面有Java .exe,并且Java应用程序是从命令行运行的)。这就是为什么File(".")总是返回C:\Windows\system32,以及为什么从macOS或*nix实现运行示例时总是返回与Windows不同的结果。

不幸的是,就我在二十年的Java编码中所发现的,对于这个问题并没有普遍正确的答案,除非您想使用JNI调用创建自己的本机启动器可执行文件,并在启动时从本机启动器代码中获取当前工作目录。在某些情况下,其他事物至少会有一些细微差别。