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

如何获取当前目录?


当前回答

这将给你当前工作目录的路径:

Path path = FileSystems.getDefault().getPath(".");

这将为您提供工作目录中名为“Foo.txt”的文件的路径:

Path path = FileSystems.getDefault().getPath("Foo.txt");

编辑: 获取当前目录的绝对路径。

Path path = FileSystems.getDefault().getPath(".").toAbsolutePath();

*更新* 获取当前工作目录:

Path path = FileSystems.getDefault().getPath("").toAbsolutePath();

其他回答

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

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

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

System.getProperty("user.dir");

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

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

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

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

var path = Path.of(".").toRealPath();
this.getClass().getClassLoader().getResource("").getPath()

通常,作为File对象:

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

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

getCwd().getAbsolutePath()