开发者

why does new File("") not provide an existing directory?

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:

  1. If I get the full path of "", what is it? D:\workspace\jumbo-converters\jumbo-converters-compchem

  2. Is "" a real directory? No.

  3. Does "" exist in some way? No.

  4. If I get the full path of "D:\workspace\jumbo-converters\jumbo-converters-compchem", what is it? D:\workspace\jumbo-converters\jumbo-converters-compchem

  5. Is "D:\workspace\jumbo-converters\jumbo-converters-compchem" a real directory? Yes.

  6. 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"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜