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

如何获取当前目录?


当前回答

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调用创建自己的本机启动器可执行文件,并在启动时从本机启动器代码中获取当前工作目录。在某些情况下,其他事物至少会有一些细微差别。

通常,作为File对象:

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

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

getCwd().getAbsolutePath()

你可以使用new File("./")。这样isDirectory()返回true(至少在Windows平台上)。另一方面,new File("") isDirectory()返回false。

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

参见:路径操作(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

对我来说,这就是我上课的地方。

以相对方式构造路径(不使用前分隔符来表示正在构造绝对路径)将使用这个相对路径作为起点。