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

如何获取当前目录?


当前回答

这是一个非常令人困惑的主题,在提供真正的解决方案之前,我们需要了解一些概念。

File和NIO File Api使用相对路径“”或“。”在内部使用系统参数“user”。Dir”的值来确定返回位置。 “用户。dir”的值基于USER工作目录,该值的行为取决于操作系统和jar的执行方式。 例如,使用文件资源管理器从Linux执行JAR(双击打开它)将设置user。不管jar的位置如何,都可以使用用户的主目录。如果从命令行执行同一个jar,它将返回jar的位置,因为对jar位置的每个cd命令都修改了工作目录。

话虽如此,解决方案采用Java NIO,文件还是“用户”。Dir”属性将以“user. Dir”的方式适用于所有场景。Dir”的值正确。

String userDirectory = System.getProperty("user.dir");
String userDirectory2 = new File("").getAbsolutePath();
String userDirectory3 = Paths.get("").toAbsolutePath().toString();

我们可以使用以下代码:

new File(MyApp.class.getProtectionDomain()
                     .getCodeSource()
                     .getLocation()
                     .toURI().getPath())
     .getParent();

来获得已执行JAR的当前位置,我个人使用以下方法来获得预期的位置并覆盖“user”。Dir”的系统属性。所以,以后当使用其他方法时,我总是会得到期望值。

更多细节在这里-> https://blog.adamgamboa.dev/getting-current-directory-path-in-java/

    public class MyApp {
      
      static {
        //This static block runs at the very begin of the APP, even before the main method.
        try{
          File file = new File(MyApp.class.getProtectionDomain().getCodeSource()
                           .getLocation().toURI().getPath());
          String basePath = file.getParent();
          //Overrides the existing value of "user.dir"
          System.getProperties().put("user.dir", basePath);
        }catch(URISyntaxException ex){
          //log the error
        }
      }
     
      public static void main(String args []){
        //Your app logic
        
        //All these approaches should return the expected value
        //regardless of the way the jar is executed.
        String userDirectory = System.getProperty("user.dir");
        String userDirectory2 = new File("").getAbsolutePath();
        String userDirectory3 = Paths.get("").toAbsolutePath().toString();
      }
    }

我希望这些解释和细节对其他人有帮助…

其他回答

我最喜欢的方法是从附加到当前运行进程的系统环境变量中获取。在这种情况下,您的应用程序由JVM管理。

String currentDir = System.getenv("PWD");
/*
 /home/$User/Documents/java
*/

查看其他你可能会发现有用的环境变量,如home dir, os版本........

//Home directory
String HomeDir = System.getEnv("HOME");


//Outputs for unix
/home/$USER

//Device user
String user = System.getEnv("USERNAME");


//Outputs for unix
$USER

这种方法的美妙之处在于,对于所有类型的操作系统平台,所有路径都将被解析

这就是我的解决方案

File currentDir = new File("");

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

这里贴出来的答案没有一个对我有用。以下是行之有效的方法:

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()

Java 11及更新版本

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

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

甚至

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