新文件(“”)与新文件(“。”):功能还是错误?

时间:2011-05-04 13:00:37

标签: file io java

new File("")new File(".")产生相同的规范路径,但前一个对象是不可替代的。考虑下面的代码,以及两个对象如何返回相同的规范路径。 The documentation states规范路径是“既绝对又独特”。但只有用“。”创建的文件。参数实际上是可用的。

不应该在某个时候抛出异常吗?在空字符串构造函数调用中(因为创建的对象似乎没有效果),或者至少在getCanonicalPath中(至少声明IOException)?

import java.io.File;
import java.io.IOException;

public abstract class Test {

    public static void main(String[] args) throws Exception {
        testFile("");
        testFile(".");
    }

    private static void testFile(String arg) throws IOException {
        System.out.format("File constructor argument: \"%s\"\n", arg);
        File g = new File(arg);
      System.out.format("toString()            = \"%s\"\n", g.toString());
        System.out.format("getAbsolutePath()     = \"%s\"\n", g.getAbsolutePath());
        System.out.format("getAbsoluteFile()     = \"%s\"\n", g.getAbsoluteFile());
        System.out.format("getgetCanonicalPath() = \"%s\"\n", g.getCanonicalPath());
        System.out.format("getgetCanonicalFile() = \"%s\"\n", g.getCanonicalFile());
        System.out.format("exists()              = %s\n", g.exists());
        System.out.format("isDirectory()         = %s\n", g.isDirectory());
        System.out.println();
  }
}

它产生的输出:

File constructor argument: ""
toString()            = ""
getAbsolutePath()     = "C:\usr\workspace\Test"
getAbsoluteFile()     = "C:\usr\workspace\Test"
getgetCanonicalPath() = "C:\usr\workspace\Test"
getgetCanonicalFile() = "C:\usr\workspace\Test"
exists()              = false
isDirectory()         = false

File constructor argument: "."
toString()            = "."
getAbsolutePath()     = "C:\usr\workspace\Test\."
getAbsoluteFile()     = "C:\usr\workspace\Test\."
getgetCanonicalPath() = "C:\usr\workspace\Test"
getgetCanonicalFile() = "C:\usr\workspace\Test"
exists()              = true
isDirectory()         = true

3 个答案:

答案 0 :(得分:14)

在使用带有空String的构造函数时,您将创建一个具有两个属性的File实例:

  • 它实际上并不存在。
  • 其绝对路径名是“空抽象路径名”

使用文件(“。”)时,您创建了一个不同的文件:

  • 它存在于文件系统
  • 其绝对路径名包含“。”字符

第二个文件存在,而不是第一个。因此,第二个文件是唯一一个应该遵守getCanonicalPath中解释的规则的文件:

  

表示现有文件或目录的每个路径名都具有唯一的规范形式。

由于第一个文件不真实,他们的规范路径相同的事实是没有意义的。

因此,你指出的行为不是一个错误。这是我们对JVM的期望。

You'll find all the infos in the javadoc

答案 1 :(得分:10)

通过将空字符串传递给构造函数,您将创建一个空的“抽象路径名”。来自java.io.File Javadoc

  

如果给定的字符串是空的   字符串,然后结果为空   抽象路径名。

在这种情况下,'空抽象路径名'实际上不存在,因此exists()计算为false。您获取空字符串目录的原因在getAbsolutePath的{​​{3}}中进行了描述:

  

如果此抽象路径名为空   抽象路径名然后是路径名   当前用户目录的字符串,   由系统属性命名   user.dir,返回。

答案 2 :(得分:5)

根据javaDocs:

表示现有文件或目录的每个路径名 都有唯一的规范形式。

在您的第一个示例中,您指的是“没有名称的文件”。

由于那个不存在,我不认为新文件(“”)和新文件(“。”)产生相同规范路径的错误。

相关问题