【问题标题】:Do java.io.File(String parent, String child) and java.io.File(String pathname) do the same work?java.io.File(String parent, String child) 和 java.io.File(String pathname) 做同样的工作吗?
【发布时间】:2021-05-04 05:47:36
【问题描述】:

我读过Oracle documentation,但我还是不明白。例如:

File("/storage/emulated/0", "directory").mkdirs()

File("/storage/emulated/0/directory").mkdirs()

在这种情况下它们是否相同?

【问题讨论】:

标签: java


【解决方案1】:

所以取自 OpenJDK 8(https://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/io/File.java) 的代码,唯一的字符串构造函数是:

public File(String pathname) {

    if (pathname == null) {

        throw new NullPointerException();

    }

    this.path = fs.normalize(pathname);

    this.prefixLength = fs.prefixLength(this.path);

}

而对于这两个String Constructor是:

 public File(String parent, String child) {

        if (child == null) {

            throw new NullPointerException();

        }

        if (parent != null) {

            if (parent.equals("")) {

                this.path = fs.resolve(fs.getDefaultParent(),

                                       fs.normalize(child));

            } else {

                this.path = fs.resolve(fs.normalize(parent),

                                       fs.normalize(child));

            }

        } else {

            this.path = fs.normalize(child);

        }

        this.prefixLength = fs.prefixLength(this.path);

    }

其中 normalize 只是删除像 .和 .. 因此,您可能会看到父级和子级对文件系统进行了额外的调用。但是这个电话只意味着“如果路径对父母来说是真实的,请给我通往孩子的路径”。因此,在您的通话中,它们将导致相同的行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-23
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    相关资源
    最近更新 更多