java:new File(“”,“name”)!= new file(“name”)? (带有空字符串的文件构造函数)

今天注意到这一点。

鉴于java进程(windows)的PWD中存在名为“existing”的文件。

new File("existing").exists() => true new File("", "existing").exists() => false new File(".", "existing").exists() => true 

我原本预计,从javadoc系统依赖的默认目录将是“。”。 这一切都是真的,所以这出乎意料。

思考?

谢谢!

-roger-

两个参数构造函数需要父目录名,因此第二行会查找其相对路径为“/ existing”的文件。 在linux类型系统上,“/”是根(据我所知),因此/ existing不太可能存在。 在Windows上,我不确定它默认是什么解释,但如果我打开一个命令行并说cd /Desktop (工作目录是我的用户文件夹),它说它找不到指定的路径。

这就是发生的事情。 但我同意,因为这令人困惑

 new File("", "test").getAbsolutePath() => /test new File(".", "test").getAbsolutePath() => ${pwd}/test 

我不知道为什么会这样,因为我认为第一个也是pwd。

我记得遇到过这么多的月亮,所以我做了一些挖掘实际的来源。 以下是File.java的相关源文档:

 /* Note: The two-argument File constructors do not interpret an empty parent abstract pathname as the current user directory. An empty parent instead causes the child to be resolved against the system-dependent directory defined by the FileSystem.getDefaultParent method. On Unix this default is "/", while on Microsoft Windows it is "\\". This is required for compatibility with the original behavior of this class. */ 

因此,非显而易见的行为似乎是由于遗留原因造成的。

来自java.io.File :

 If parent is the empty string then the new File instance is created by converting child into an abstract pathname and resolving the result against a system-dependent default directory. 

没有提到默认目录是什么。

请记住,“”与null不同。 正是如此

 new File("", "existing").exists() 

不承担。 目录。 正如@Dylan Halperin所说,在Linux上使用“”指向root /目录,正如我发现使用此代码:

 import java.io.*; class FileTest { public static void main(String args[]) { String nullStr = null; File f1 = new File(nullStr, "f1"); File f2 = new File("", "tmp"); System.out.println("f1.exists(): " + f1.exists()); System.out.println("f2.exists(): " + f2.exists()); } } 

输出:

f1.exists():true
f2.exists():true

是的,我在工作目录中创建了一个名为“f1”的文件。