java: new File(“”, “name”) != new File(“name”) ? (file constructor with empty string)

后端 未结 5 875
野趣味
野趣味 2021-01-20 22:55

Noticed this today.

Given that a file named \"existing\" exists in the PWD of a java process (windows).

new File(\"existing\").exists() => true
         


        
5条回答
  •  有刺的猬
    2021-01-20 23:13

    I remember encountering this many moons ago, so I did some digging in the actual source. Here is the relevant source documentation from 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. */
    

    So, the non-obvious behavior appears to be due to legacy reasons.

提交回复
热议问题