When, in the course of human events, it becomes necessary to parse and create directory paths in your Java applications, you'll need to know how to do it properly.

And you might find that you need either File.pathSeparator or File.separator.

In this guide, I'll explain the difference.

File.pathSeparator

First up is File.pathSeparator. That's the one you use when you want to separate different directories in a string.

On Windows, File.pathSeparator is a semicolon. But on UNIX it's a colon.

So if you're on a Windows platform right now and type path at the command prompt followed by the Enter key, you'll see something like this:

PATH=C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin;C:\Program Files\Common Files\Oracle\Java\javapath;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Python39\Scripts\;C:\Python39\;C:\Program Files (x86)\Common Files\Intel\Shared Libraries\redist\intel64\compiler;C:\Windows\system32;

See all those semicolons in there separating different directories? Those are the path separators.

Now do echo $PATH on a UNIX command line and you'll see something like this:

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/usr/local/jdk-11.0.2/bin:/root/bin

The directories are separated by a colon.

So if you want to construct a String object in your Java application that separates multiple directories, you'd use File.pathSeparator.

Truth be told, though, you probably won't need File.pathSeparator that much.

File.separator

Next up is File.separator. You'll use that to separate path segments.

On Windows platforms, File.separator is a backslash. But it's a forward slash on UNIX.

For example, consider the following directory on Windows:

C:\Users\carey\source\repos\admin-console

See all those backslashes in there? They're separators. They separate parent directories from subdirectories.

But on UNIX a path looks something like this:

/usr/local/jdk-11.0.2/bin

The separator there is a forward slash.

File.separator exists so that when you construct a full path from a String object, you won't need to worry about the underlying operating system.

But there's a caveat.

It's Easier Than You Think

The JVM is smart enough to recognize forward slashes as path segment separators on any platform.

Yes, even Windows.

So if you create a directory from a String object that looks like this:

"C:/Users/carey/source/repos/admin-console"

It will work just fine with those forward slashes.

Yes, even on Windows.

So the folks who developed the Java language made your life really easy when it comes to this kind of stuff.

But I think it's still a best-practice to use File.separator.

Wrapping It Up

Now you know when to use File.pathSeparator and when to use File.separator.

If you have any requirements that involve building OS-level paths, use them as you see fit.

Have fun!

Photo by Andrea Piacquadio from Pexels