I am using Eclipse+Java and trying to create files under my current project. I have used new File("")
and do not understand its behaviour.
File dir = new File("");
System.out.println(dir.getAbsolutePath()+" | "+dir.isDirectory()+" | "+dir.exists());
String absolutePathname = dir.getAbsolutePath();
dir = new File(absolutePathname);
System.out.println(dir.getAbsolutePath()+" | "+dir.isDirectory()+" | "+dir.exists());
results in:
D:\workspace\jumbo-converters\jumbo-converters-compchem | false | false
D:\workspace\jumbo-converters\j开发者_运维百科umbo-converters-compchem | true | true
Why can I have two files which have the same absolute pathname one of which exists and one of which does not?
I am using Java 1.6 and Eclipse Helios
File dir = new File(""); means a file with name "empty string" and naturally this file doesn't exist and it is not a directory. To refer current directory, use File dir = new File("."); look at this code:
File dir = new File("");
System.out.println(dir.getAbsolutePath()+" | "+dir.isDirectory()+" | "+dir.exists());
System.out.println("file name is: |" + dir.getName() + "|");
String absolutePathname = dir.getAbsolutePath();
dir = new File(absolutePathname);**
System.out.println(dir.getAbsolutePath()+" | "+dir.isDirectory()+" | "+dir.exists());
System.out.println("file name is: |" + dir.getName() + "|");
notice a different file name:
C:\Program Files (x86)\Java\jdk1.6.0_21\bin | false | false
file name is: ||
C:\Program Files (x86)\Java\jdk1.6.0_21\bin | true | true
file name is: |bin|
Because, you're asking the following questions:
If I get the full path of "", what is it?
D:\workspace\jumbo-converters\jumbo-converters-compchem
Is "" a real directory?
No.
Does "" exist in some way?
No.
If I get the full path of "D:\workspace\jumbo-converters\jumbo-converters-compchem", what is it?
D:\workspace\jumbo-converters\jumbo-converters-compchem
Is "D:\workspace\jumbo-converters\jumbo-converters-compchem" a real directory?
Yes.
Does "D:\workspace\jumbo-converters\jumbo-converters-compchem" exist in some way?
Yes.
The reason #1 works is because any relative path (i.e., a path that doesn't start with /
or a drive) can be made absolute by combining it with the current directory. So:
"D:\workspace\jumbo-converters\jumbo-converters-compchem" + "" == "D:\workspace\jumbo-converters\jumbo-converters-compchem"
精彩评论