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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s