Portable filenames in Java

By Steve Claridge on 2014-03-15.

You should always use a forward-slash in a filename. Java will substitute forward-slashes for back-slashes if it is running on Windows, which means you can define:


instead of having to escape each back-slash:


The first version is a bit more readable but it still isn't portable because you have the c: at the start, which won't work on Linux. Luckily Java has another trick up its sleeve: you don't need to specify the Windows drive name if you are accessing a file on the same drive as was used to execute the JVM. Lets say we are logging to /tmp/application.log on Linux and to the c:\tmp\application.log file on Windows, we only need to specify the filename once in our code as:


Java will convert the forward-slashes to back-slashes on Windows and it will also automatically load the file from the C: drive as long as the Java application itself was also run from the C: drive.

Portable filenames are easy in Java. Write Once Run Anywhere.