new File("")
并new File(".")
产生相同的规范路径,但前一个对象是不可分解的。考虑下面的代码,以及两个对象如何返回相同的规范路径。该文档指出规范路径是“绝对的和唯一的”。但是只有用“。”创建的文件。论点实际上是有用的。
难道不应该在某个时候抛出异常吗?是在空字符串构造函数调用中(因为创建的对象似乎无效),还是至少在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
在将构造函数与空字符串一起使用时,您将创建一个具有两个属性的File实例:
使用File(“。”)时,您将创建另一个文件:
此第二个文件存在,而不是第一个。因此,第二个文件是唯一应该遵守getCanonicalPath中解释的规则的文件:
表示现有文件或目录的每个路径名都具有唯一的规范形式。
由于第一个文件不是真实的,因此它们的规范路径相等是没有意义的。
因此,您所指出的行为不是错误。这是我们对JVM的期望。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句