Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Noticed this today.

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

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

I would have anticipated, from the javadoc that the system dependent default directory would be "." and these all be true, so this unexpected.

Thoughts?

Thanks!

-roger-

like image 934
rogerdpack Avatar asked Jan 30 '26 04:01

rogerdpack


2 Answers

This is what's happening. But I agree because this is confusing

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

I have no idea why this is the case because I had assumed it would also be pwd for the first one.

like image 52
Amir Raminfar Avatar answered Jan 31 '26 20:01

Amir Raminfar


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.

like image 43
Nathan Ryan Avatar answered Jan 31 '26 20:01

Nathan Ryan