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

如何获取当前目录?


当前回答

代码:

public class JavaApplication {
  public static void main(String[] args) {
    System.out.println("Working Directory = " + System.getProperty("user.dir"));
  }
}

这将打印初始化应用程序的当前目录的绝对路径。


解释:

从文档中可以看到:

java。IO包使用当前用户目录解析相对路径名。当前目录表示为系统属性,即user。dir,是调用JVM的目录。

其他回答

在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可能被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();
    }
}

我在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”)文档

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

假设您试图在eclipse或netbean中运行项目,或者在命令行中独立运行项目。我已经写了一个方法来解决它

public static final String getBasePathForClass(Class<?> clazz) {
    File file;
    try {
        String basePath = null;
        file = new File(clazz.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
        if (file.isFile() || file.getPath().endsWith(".jar") || file.getPath().endsWith(".zip")) {
            basePath = file.getParent();
        } else {
            basePath = file.getPath();
        }
        // fix to run inside eclipse
        if (basePath.endsWith(File.separator + "lib") || basePath.endsWith(File.separator + "bin")
                || basePath.endsWith("bin" + File.separator) || basePath.endsWith("lib" + File.separator)) {
            basePath = basePath.substring(0, basePath.length() - 4);
        }
        // fix to run inside netbean
        if (basePath.endsWith(File.separator + "build" + File.separator + "classes")) {
            basePath = basePath.substring(0, basePath.length() - 14);
        }
        // end fix
        if (!basePath.endsWith(File.separator)) {
            basePath = basePath + File.separator;
        }
        return basePath;
    } catch (URISyntaxException e) {
        throw new RuntimeException("Cannot firgue out base path for class: " + clazz.getName());
    }
}

要使用,在任何你想要读取文件的基路径的地方,你可以将你的锚类传递给上面的方法,结果可能是你需要的东西:D

最好的