In this article, we will present how to get a file path separator in Java. A file separator is platform-dependent what means in Unix we will have a different separator than in Windows OS. That's why it is important to use Java-built methods to retrieve it when we are working with files.
We can get file path separator in three ways:
FileSystems.getDefault().getSeparator() methodfrom the latest Java NIO,
File.separatorfrom Java IO API.
2. Get a file path separator using a system property
In system properties JVM holds information about the configuration of the current working environment such as a current version of Java runtime ("java.version"), current user ("user.name"), and also the character used to separate elements of the file pathname ("file.separator").
Let's check the example code that makes use of that system properties to get file path separator:
System.getProperties() can be overridden using
System.setProperty(String key, String value) or with command line parameters
-Dfile.separator=/, so we could not rely on this parameter in 100%.
3. Retrieve path separator with
Another method to get a file path separator comes with Java NIO API. This API provides a dedicated method called on
FilesSystems class to get the name of the separator used to separate names in a path string.
The following example shows how to use a platform-independent method from Java NIO to get a file path separator:
4. File path separator using Java IO
In older Java IO API there is also a property that holds a file path separator
We recommend using the
FileSystems.getDefault().getSeparator() method that was provided in Java NIO.
This article covered methods used to get a file path separator in Java. It is important to use methods available in Java IO or NIO API, instead of hardcoded values. This will prevent unexpected exceptions and errors when working with files in Java applications.
As always code snippets used in this article are available under the GitHub repository.