我想使用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™教程>基本类>基本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实现中定义不同。对于Java 7之前的某些版本,没有一致的方法来获取工作目录。您可以通过使用-D启动Java文件并定义一个变量来保存信息来解决这个问题

类似的

java -D com.mycompany.workingDir="%0"

这并不完全正确,但你可以理解。然后System.getProperty(“com.mycompany.workingDir”)……

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

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

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

Java 11及更新版本

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

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

甚至

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

使用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());
    }
}

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