Woozle Wuzzle
java.io.File gotcha!

File.isDiectory() and File.isFile() are not mutually exclusive. This is commonly seen in the case:

if(file.isDirectory())
    // do something with a directory
else 
    // do something with a file

Unfortunately, the above is true if and only if File.exists() returns true. This is in the javadoc for the methods but it's common to assume that file and directory are mutually exclusive.

Since it is possible for a file to be removed between File.exists() and the corresponding File.isDiectory() and File.isFile(), it seems that best practices dictates that code similar to the following is used:

if(file.isDirectory())
    // do something with a directory
else if(file.isFile()
    // do something with a file
else
    // do something with a non-existing file

A side note to this: File.isDiectory() and File.isFile() will actually touch the native file system. It does not just check for a trailing slash or some other such thing.

Comments
Post a comment













Remember personal info?






Creative Commons License Unless otherwise expressly stated, all original material of whatever nature created by Rob Grzywinski and included in this weblog and any related pages, including the weblog's archives, is licensed under a Creative Commons License.