Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find out if a File is a file or directory if it does not exist?

Tags:

java

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?

like image 751
Amanda S Avatar asked Aug 14 '09 18:08

Amanda S


2 Answers

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.

like image 172
Mikael Auno Avatar answered Oct 30 '22 11:10

Mikael Auno


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
like image 28
Stephen C Avatar answered Oct 30 '22 10:10

Stephen C