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

如何获取当前目录?


当前回答

这是我的银弹,当困惑的时刻冒泡。(把它称为主要的第一件事)。例如,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

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

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

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

System.getProperty(“java.class.path”)

当前工作目录在不同的Java实现中定义不同。对于Java 7之前的某些版本,没有一致的方法来获取工作目录。您可以通过使用-D启动Java文件并定义一个变量来保存信息来解决这个问题

类似的

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

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

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

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

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