Creating a new File instance with a parent directory returns 一个 File inside root instead of the parent

Creating a new File instance with a parent directory returns a File inside the root instead of the parent

我有这个方法可以得到我的Java程序在运行里面的目录。

public File getWorkingDir() {
    Path path = Paths.get("");
    
    return path.toFile(); // Returns "D:\users\Simon\myprogram"
}

但是当我创建一个新的 File 实例并将此目录作为其父目录时,它 returns 在驱动器的根目录中有一个 File

File file = new File(getWorkingDir(), "testfile");

我原以为该文件的绝对路径是 D:\users\Simon\myprogram\testfile,但实际上是 D:\testfile.

Paths.get 没有返回您期望的结果。 documentation 关于它的参数是这样说的:

A Path representing an empty path is returned if first is the empty string and more does not contain any non-empty strings.

必须解析一个空路径才能固定其在文件系统中的位置。 File class 的解析行为不同。例如,File.getAbsolutePath 方法根据当前工作目录解析空路径。构造函数 File(File, String) 根据系统的默认目录解析空父目录。

通过显式解析父目录,您可能会得到想要的结果:

public String getWorkingDir() {
    Path path = Paths.get("");
    
    return path.toFile().getAbsolutePath(); // Returns "D:\users\Simon\myprogram"
}

但是,当前工作目录可以直接作为 属性:

String workingDir = System.getProperty("user.dir");