Reputation: 536
When I create a File object like
File f = new File("c:")
and then call the method isDirectory()
, it returns true
. Why is that?
The program is suppose to show all files in that directory and works fine except when Im using the "c:". It is not accessing "c:\", not the home path, but the directory the program is executing from. I really don't understand.
Upvotes: 2
Views: 430
Reputation: 137
Try C:\
instead.
File f = new File("C:\\");
System.out.println(f.getAbsolutePath());
System.out.println(f.isDirectory());
System.out.println(f.isFile());
Output:
C:\
true
false
Upvotes: -1
Reputation: 1553
This is an interesting question. I'll try to expand on your question (questions should always come with an SSCCE whenever possible)...
Take this code for example:
public class Main{
public static void main(String[] args){
File f = new File("C:\\");
System.out.println("C:\\ is directory: " + f.isDirectory());
System.out.println("C:\\ exists: " + f.exists());
System.out.println("C:\\ absolute path: " + f.getAbsolutePath());
System.out.println();
f = new File("C:");
System.out.println("C: is directory: " + f.isDirectory());
System.out.println("C: exists: " + f.exists());
System.out.println("C: absolute path: " + f.getAbsolutePath());
System.out.println();
f = new File("X:");
System.out.println("X: is directory: " + f.isDirectory());
System.out.println("X: exists: " + f.exists());
System.out.println("X: absolute path: " + f.getAbsolutePath());
System.out.println();
}
}
(Note that I do have a C: drive, I do not have an X: drive) This results in this output:
C:\ is directory: true C:\ exists: true C:\ absolute path: C:\
C: is directory: true C: exists: true C: absolute path: C:\Users\kworkman\Desktop\Tests
X: is directory: false X: exists: false X: absolute path: X:
So it seems to handle the C:\ correctly, but C: by itself results in strange output for a directory that doesn't actually exist. This is made stranger because it seems to handle the X: case correctly.
Upvotes: 0
Reputation: 33283
In Windows, a current working directory is kept for each drive (A:, B:, C: etc).
When you use a drive without specifying a directory, you are referring to the current working directory of that drive.
C: refers to the current working directory of drive C:
C:\ refers to the root directory of drive C:
In your case, the current working directory for C: is the directory where the program file resides.
Upvotes: 6