我想使用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.nio.file.Paths.get(
  getClass().getProtectionDomain().getCodeSource().getLocation().toURI()
);

编辑:在我的代码的最终版本:

URL myURL = getClass().getProtectionDomain().getCodeSource().getLocation();
java.net.URI myURI = null;
try {
    myURI = myURL.toURI();
} catch (URISyntaxException e1) 
{}
return java.nio.file.Paths.get(myURI).toFile().toString()

其他回答

我在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”)文档

这就是我的解决方案

File currentDir = new File("");

Java 11及更新版本

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

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

甚至

String cwd = Path.of("").toAbsolutePath().toString();
this.getClass().getClassLoader().getResource("").getPath()

以下内容适用于Java 7及更高版本(请参阅这里的文档)。

import java.nio.file.Paths;

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