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

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.


Why not just wrap them in a call to File#exists()?

File file = new File(...);
if (file.exists()) {

    // call isFile() or isDirectory()

}

By doing that, you've effectively negated the "exists" portion of isFile() and isDirectory(), since you're guaranteed that it does exist.


It's also possible that I've misunderstood what you're asking here. Given the second part of your question, are you trying to use isFile() and isDirectory() on non-existent files to see if they look like they're files or directories?

If so, that's going to be tough to do with the File API (and tough to do in general). If /foo/bar/baz doesn't exist, it's not possible to determine whether it's a file or a directory. It could be either.


Sounds like you know what you want, according to your update: if the path doesn't exist and the path has an extension it's a file, if it doesn't it's a directory. Something like this would suffice:

private boolean isPathDirectory(String myPath) {
    File test = new File(myPath);

    // check if the file/directory is already there
    if (!test.exists()) {
        // see if the file portion it doesn't have an extension
        return test.getName().lastIndexOf('.') == -1;
    } else {
        // see if the path that's already in place is a file or directory
        return test.isDirectory();
    }
}