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-
From java.io.File:
There's no mention of what the default directory is.
The two argument constructor expects a parent directory name, so your second line looks for a file whose relative path is "/existing". On a linux type system, "/" is the root (as far as I know), so /existing is very unlikely to exist. On windows, I'm not sure what it interprets that as by default, but if I open up a command line and say
cd /Desktop
(working directory being my user folder) it says it can't find the path specified.This is what's happening. But I agree because this is confusing
I have no idea why this is the case because I had assumed it would also be pwd for the first one.
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:
So, the non-obvious behavior appears to be due to legacy reasons.
Remember that "" is NOT the same as null. Thusly
does not assume the . directory. As @Dylan Halperin said, on Linux using "" directs to the root / directory, as I found using this code:
Output:
Yes, I had created a file named "f1" in the working directory.