【问题标题】:Why new File(File parent, String childName) behave unobvious?为什么 new File(File parent, String childName) 表现得不明显?
【发布时间】:2016-05-07 00:15:21
【问题描述】:

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

new File("");

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

new File("image");

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

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

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

如果parent 是空的抽象路径名,那么新的 File 实例是通过转换 child 创建的 转换为抽象路径名并针对 a 解析结果 系统相关的默认目录。

但是为什么呢?有什么理由吗?还是“仅仅因为”?为什么如果我将指向 current 目录的new File("") 作为父级,我会收到 root 目录作为父级的子级?

【问题讨论】:

  • 使用new File(".") 指向工作目录...
  • 这肯定更多地归结于new File("") 的行为:“如果给定的字符串是空字符串,那么结果就是空的抽象路径名。”
  • @fabian 我使用new File(null, "image") 构造函数为自己解决了这个问题,但问题不在于它。
  • new File(File, String): "如果 parent 是空的抽象路径名,则通过将 child 转换为抽象路径名并根据系统相关的默认目录解析结果来创建新的 File 实例。"
  • @AndyTurner 是的,我想你可能就在这里,new File(String) 在文档中有以下文字:“如果给定的字符串是空字符串,那么结果是空的抽象路径名。”并没有说明当前或任何其他目录。操作系统像工作目录一样解释为空。这样new File("")指向工作目录就可以被认为是无证行为。

标签: java file


【解决方案1】:

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.getDefaultParentFileSystem.resolveFileSystem.normalize 是抽象的,因此具体行为不会立即显现;但是,假设不同的代码路径会导致不同的行为并非没有道理。

【讨论】:

    猜你喜欢
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    • 2011-04-17
    • 1970-01-01
    相关资源
    最近更新 更多