new File(“”) vs. new File(“.”): 功能还是 Bug?
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