我想使用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 11,你还可以使用:

var path = Path.of(".").toRealPath();

其他回答

这就是我的解决方案

File currentDir = new File("");

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

类似的

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

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

试试这样的东西,我知道我的答案晚了,但这个明显的事情发生在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盘的另一个目录中进行测试工作正常

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

Java 11及更新版本

这个解决方案比其他解决方案更好,更可移植:

Path cwd = Path.of("").toAbsolutePath();

甚至

String cwd = Path.of("").toAbsolutePath().toString();