java - 为什么 new File(File Parent, String childName) 表现不明显?

标签 java file

如果我创建这样的文件,我会因为以下行为而堆积一段时间:

new File("");

然后它将指向项目工作目录,在我的例子中是 C:/project/ 。如果创建这样的文件:

new File("image");

然后它将相对于项目目录,在我的例子中是C:/project/image/。一切都很好,但是如果我使用 new File(File Parent, String childName) 构造函数创建文件,如下所示:

new File(new File(""), "image");

然后它将指向C:/image/,我从根目录开始。我发现这是有记录的行为:

If parent is the empty abstract pathname then the new File instance is created by converting child into an abstract pathname and resolving the result against a system-dependent default directory.

但是为什么呢?有什么理由吗?还是“只是因为”?为什么如果我提供指向当前目录的new File(""),作为父目录,我将收到具有root的子目录目录作为父目录?

最佳答案

source code显示了为什么存在差异:

/**
 * The FileSystem object representing the platform's local file system.
 */
private static final FileSystem fs = DefaultFileSystem.getFileSystem();

// Snip.

public File(File parent, String child) {
    if (child == null) {
        throw new NullPointerException();
    }
    if (parent != null) {
        if (parent.path.equals("")) {
            this.path = fs.resolve(fs.getDefaultParent(),
                                   fs.normalize(child));
        } else {
            this.path = fs.resolve(parent.path,
                                   fs.normalize(child));
        }
    } else {
        this.path = fs.normalize(child);
    }
    this.prefixLength = fs.prefixLength(this.path);
}

对比

public File(String pathname) {
    if (pathname == null) {
        throw new NullPointerException();
    }
    this.path = fs.normalize(pathname);
    this.prefixLength = fs.prefixLength(this.path);
}

即如果您通过new File("")作为parent参数,FileSystem解析路径时会考虑 的默认父级。

所有方法FileSystem.getDefaultParent , FileSystem.resolveFileSystem.normalize是抽象的,因此具体行为不是立即显而易见的;但是,假设不同的代码路径将导致不同的行为并非没有道理。

关于java - 为什么 new File(File Parent, String childName) 表现不明显?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37066657/

相关文章:

C# 文件处理 - 创建文件并打开

java - 我正在寻找给定场景的规范的替代方案

java - 当您不知道文件所在位置时,如何读取文件?

python - 使用 'with' 语句后的变量范围

java - 在不在 Activity 的 Jersey 错误范围内运行的代码中检测到 HK2 故障

file - 读取文本文件中的行,排序,然后覆盖文件

java - 读/写大文件的最简单格式

java - AWS 分区加载器

java - 通过 JDBC 查询登录时出现 NullPointerException 错误

java - 如何使用带有无效返回参数的 JPA 2.1 @NamedStoredProcedureQueries?