File.isFile() and File.isDirectory() both return false not only when the File is not the specified type, but also when the File itself does not exist on the filesystem. How can I determine whether the File represents a file or a directory when it does not exist?
views:
169answers:
5Test File.exists() first.
Pseudo-Code (because I don't do Java :) ):
If File.Exists()
{
If File.isFile()
{
bIsFile = true;
}elseif File.isFolder()
{
bIsFolder = true;
}else
{
//Handle error condition here
}
}else
{
//It does not exist. Handle that here if you care to
}
In general, a specific path can represent both a directory and a file. Until there is either a directory or a file created at that path, the notion of it being for one or the other is invalid.
There is however a special case. If the path ends with a path separator ('/' on Unix-like systems, '\' on Windows and maybe something completely different on other systems), then at least on Unix-like systems the path cannot be that of a file. I do not know if this is valid for all systems though.
You can't
The file must exists first in order to know what it IS ( I understand that if the file does not exist it IS nothing yet )
The javadoc says in both cases:
true if and only if the file denoted by this abstract pathname exists and [...]
A file that does not exists yet may be both potentially.
I think the answer is that you can't. Part of the reason is that it just doesn't exist. The rest of the reason has to do with the system-independence of Java. Depending on what operating system you're running on, there isn't really a difference between a file and a directory. In UNIX for example, everything is a file. Pipes, directories, links -- they're all technically files.
As it stands, the abstract pathname referenced by the File object could be either one -- until you perform either mkdir() or createNewFile() on it.
Your question is like asking this:
"How can I tell if this box contains a cat or a dog when it is empty?"
On the face of it, this question is nonsensical, and so is yours. If a File is a path refers to a non-existent file system object (i.e. to "nothing") then asking whether that "nothing" >>is<< a file or a directory is meaningless. It is obviously neither.
Specifically, at any instant in time all of the following predicates hold:
file.exists() == false IMPLIES
file.isDirectory() == false AND file.isFile() == false
file.isDirectory() == true OR file.isFile() == true IMPLIES
file.exists() == true
file.isDirectory() == true IMPLIES
file.isFile() == false
file.isFile() == true IMPLIES
file.isDirectory() == false