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

如何获取当前目录?


当前回答

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

其他回答

this.getClass().getClassLoader().getResource("").getPath()

使用Windows用户。dir按预期返回目录,但当你以高权限启动应用程序时(以admin身份运行),在这种情况下,你会得到C:\WINDOWS\system32

我在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 11,你还可以使用:

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

通常,作为File对象:

File getCwd() {
  return new File("").getAbsoluteFile();
}

你可能想要像“D:/a/b/c”这样的全限定字符串:

getCwd().getAbsolutePath()