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

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

其他回答

我在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。

我最喜欢的方法是从附加到当前运行进程的系统环境变量中获取。在这种情况下,您的应用程序由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

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

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

这就是我的解决方案

File currentDir = new File("");