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

如何获取当前目录?


当前回答

假设您试图在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

最好的

其他回答

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

试试这样的东西,我知道我的答案晚了,但这个明显的事情发生在java8的新版本,从那里问这个问题,但是..

的代码

import java.io.File;

public class Find_this_dir {

    public static void main(String[] args) {

//some sort of a bug in java path is correct but file dose not exist
        File this_dir = new File("");

//but these both commands work too to get current dir        
//      File this_dir_2 = new File(this_dir.getAbsolutePath());
        File this_dir_2 = new File(new File("").getAbsolutePath());

        System.out.println("new File(" + "\"\"" + ")");
        System.out.println(this_dir.getAbsolutePath());
        System.out.println(this_dir.exists());
        System.out.println("");
        System.out.println("new File(" + "new File(" + "\"\"" + ").getAbsolutePath()" + ")");
        System.out.println(this_dir_2.getAbsolutePath());
        System.out.println(this_dir_2.exists());
    }
}

这将工作,并向您显示当前路径,但我现在不知道为什么java无法在新文件("")中找到当前目录;此外,我使用Java8编译器…

这工作得很好,我甚至测试了它new File(new File("").getAbsolutePath());

现在你在File对象中有了当前目录(例如File对象是f then),

f.t getabsolutepath()将以String变量类型给出路径…

在非C盘的另一个目录中进行测试工作正常

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

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

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

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

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

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