Java isFile(), isDirectory() without checking for existence

aleroot picture aleroot · Dec 27, 2011 · Viewed 20.4k times · Source

I want to check if a given String is a file or a directory, i've tried the methods isFile() and isDirectory() of the File class but the problem is that if the directory or file doesn't exist these methods returns false, because as stated in the javadoc :

isFile() :

true if and only if the file denoted by this abstract pathname exists and is a normal file; false otherwise

isDirectory() :

true if and only if the file denoted by this abstract pathname exists and is a directory; false otherwise

Basically i need two methods without the exist clause ...

So i want to test if the given string complies to a directory format or complies to a file format, in a multiplatform context (so, should work on Windows, Linux and Mac Os X).

Does exist some library that provide these methods ? What could be the best implementation of these methods ?

UPDATE

In the case of a string that could be both(without extension) by default should be identified as directory, if a file with that path does not exist.

Answer

Gilbert Le Blanc picture Gilbert Le Blanc · Dec 27, 2011

So i want to test if the given string complies to a directory format or complies to a file format, in a multiplatform context (so, should work on Windows, Linux and Mac Os X).

In Windows, a directory can have an extension and a file is not required to have an extension. So, you can't tell just by looking at the string.

If you enforce a rule that a directory doesn't have an extension, and a file always has an extension, then you can determine the difference between a directory and a file by looking for an extension.