JRE 6, on Windows XP.
Instanciating two File objects with different constructors leads to inconsistent results in the File.exists()
method.
Disclaimer : the code below is an abstract, not the actual code. I do not believe this is a File.separator issue at all. I first asked to get early reactions, in case I missed a well understood issue. It now seems that resetting the user.dir
system property is one of the causes to this problem. The code below is now reproducible and usable as is. You can copy/paste the Java class and try it, it should behave consistently with what I have listed as results.
Setup:
Create the folder architecture C:\toto\tmp\sub
.
Launch the following class from within any folder which does not contain a tmp/sub
sub-folder architecture.
Code:
public class TestFileExists {
public static void main(String[] args) {
System.setProperty("user.dir", "C:\\toto\\");
File root = new File("tmp");
File sub_a = new File(root, "sub");
File sub_b = new File(root.getAbsolutePath()+"/sub");
System.out.println("sub_a path ? "+sub_a.getAbsolutePath());
System.out.println("sub_a exists ? "+sub_a.exists());
System.out.println("sub_b path ? "+sub_b.getAbsolutePath());
System.out.println("sub_b exists ? "+sub_b.exists());
System.out.println("Path equals ? "+ (sub_a.getAbsolutePath().equals(sub_b.getAbsolutePath())));
System.out.println("Obj equals ? "+ (sub_a.equals(sub_b)));
}
}
Result :
sub_a path ? C:\toto\tmp\sub
sub_a exists ? false
sub_b path ? C:\toto\tmp\sub
sub_b exists ? true
Path equals ? true
Obj equals ? false
I don't understand the line sub_a exists ? false
, and the result is not consistent from machine to machine, nor with the root initial path ant the result is now consistent with from machine to machine.
Now if you reexecute the class by calling java from the command line, from a folder which does contain a tmp/sub
sub-folder architecture (like if you call it from D:\
, having D:\tmp\sub
), you will get the expected :
sub_a path ? C:\toto\tmp\sub
sub_a exists ? true
sub_b path ? C:\toto\tmp\sub
sub_b exists ? true
Path equals ? true
Obj equals ? false
But the existence of sub_a
is clearly a false positive, because it checks the existence of another folder than the one described by the getAbsolutePath()
.
So I strongly suspect that File.exists()
depends on the actual Java execution path, and that file existence is not consistent with the absolute path, and exists()
uses another path than the "user.dir" system property to check the file system.
Any idea where this problem could come from ?