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

如何获取当前目录?


当前回答

这将给你当前工作目录的路径:

Path path = FileSystems.getDefault().getPath(".");

这将为您提供工作目录中名为“Foo.txt”的文件的路径:

Path path = FileSystems.getDefault().getPath("Foo.txt");

编辑: 获取当前目录的绝对路径。

Path path = FileSystems.getDefault().getPath(".").toAbsolutePath();

*更新* 获取当前工作目录:

Path path = FileSystems.getDefault().getPath("").toAbsolutePath();

其他回答

是什么让你认为c:\windows\system32不是你的当前目录?用户。dir属性显式为“用户的当前工作目录”。

换句话说,除非你从命令行启动Java,否则c:\windows\system32可能就是你的CWD。也就是说,如果您双击启动程序,CWD不太可能是您双击的目录。

编辑:这似乎只适用于旧的windows和/或Java版本。

试试这样的东西,我知道我的答案晚了,但这个明显的事情发生在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程序在c:\myApp\com\foo\src\service\MyTest.java,你想打印直到c:\myApp\com\foo\src\service,那么你可以尝试以下代码:

String myCurrentDir = System.getProperty("user.dir")
            + File.separator
            + System.getProperty("sun.java.command")
                    .substring(0, System.getProperty("sun.java.command").lastIndexOf("."))
                    .replace(".", File.separator);
    System.out.println(myCurrentDir);

注意:此代码仅在Windows和Oracle JRE中测试。

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

最好的

以下内容适用于Java 7及更高版本(请参阅这里的文档)。

import java.nio.file.Paths;

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