Sometimes with Java NIO, you get a hold of a Path object but you're not sure if it's a file or directory.

Fortunately, there's an easy way to find out.

And in this very brief article, I'll walk you through it.

Start With the Existential

Before you even get into whether the Path object is a file or directory, it's a great idea to first make sure it exists.

You can do that with the Files.exists() static method. Here's an example:

final Path home = Paths.get("C:/", "home");
System.err.println(Files.exists(home));

That prints true in my case because the c:/home directory does, in fact, exist.

Now let's use Java NIO to determine if it's a file or directory, even though I already gave you the answer.

Directory Check

Here's the code you'll run if you want to check if the Path object is a directory:

final Path home = Paths.get("C:/", "home");
System.err.println(Files.exists(home));
System.err.println(Files.isDirectory(home));

That prints out two (2) true statements because c:/home both exists and is a directory.

File Check

Finally, here's how to determine if the given Path object is a file instead of a directory:

final Path home = Paths.get("C:/", "home");
System.err.println(Files.exists(home));
System.err.println(Files.isDirectory(home));
System.err.println(Files.isRegularFile(home));

That will print out two trues and a false because c:/home is not a regular file.

What About the LinkOption?

If you took a peek at the JavaDocs, you might have noticed that all three of those methods let you include one or more LinkOptions as well. So what's that all about?

It's all about following sym links.

By default, the JVM will follow sym links.

But sometimes you might want to ignore sym links. To do that, just specify LinkOption.NOFOLLOW_LINKS like so:

final Path home = Paths.get("C:/", "home");
System.err.println(Files.isDirectory(home, LinkOption.NOFOLLOW_LINKS));

Wrapping It Up

There you go. Now you know how to tell if a Path object points to a file or directory.

Take what you've learned here and run with it.

Have fun!

Photo by Christina Morillo from Pexels