我想使用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 7及更高版本(请参阅这里的文档)。

import java.nio.file.Paths;

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

其他回答

这是我的银弹,当困惑的时刻冒泡。(把它称为主要的第一件事)。例如,JVM可能被IDE滑到不同的版本。这个静态函数搜索当前进程PID,并在该PID上打开VisualVM。困惑就此停止,因为你想要一切,而且你得到了……

  public static void callJVisualVM() {
    System.out.println("USER:DIR!:" + System.getProperty("user.dir"));
    //next search current jdk/jre
    String jre_root = null;
    String start = "vir";
    try {
        java.lang.management.RuntimeMXBean runtime =
                java.lang.management.ManagementFactory.getRuntimeMXBean();
        String jvmName = runtime.getName();
        System.out.println("JVM Name = " + jvmName);
        long pid = Long.valueOf(jvmName.split("@")[0]);
        System.out.println("JVM PID  = " + pid);
        Runtime thisRun = Runtime.getRuntime();
        jre_root = System.getProperty("java.home");
        System.out.println("jre_root:" + jre_root);
        start = jre_root.concat("\\..\\bin\\jvisualvm.exe " + "--openpid " + pid);
        thisRun.exec(start);
    } catch (Exception e) {
        System.getProperties().list(System.out);
        e.printStackTrace();
    }
}

使用Windows用户。dir按预期返回目录,但当你以高权限启动应用程序时(以admin身份运行),在这种情况下,你会得到C:\WINDOWS\system32

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

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

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

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

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

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