Java provides built-in mechanisms to retrieve the correct file path separator for the host operaitng system without manual OS string parsing.
The standard and most reliable approach uses File.separator, a static String field that automatically reflects the native separator ("\\" on Windows, "/" on Unix-like systems including Linux and macOS):
public class PathSeparatorExample {
public static void main(String[] args) {
String sep = java.io.File.separator;
System.out.println("Native file separator: " + sep);
// Example usage in path construction
String configPath = "etc" + sep + "app" + sep + "config.properties";
System.out.println("Constructed path: " + configPath);
}
}
For greater flexibility—such as when building paths programmatically or validating separators—java.nio.file.Paths and Path offer type-safe alternatives:
import java.nio.file.Path;
import java.nio.file.Paths;
public class NioPathExample {
public static void main(String[] args) {
Path basePath = Paths.get("var", "log", "application.log");
System.out.println("Resolved path: " + basePath);
System.out.println("Separator char: " + basePath.getFileSystem().getSeparator());
}
}
Both approaches are platform-agnostic and eliminate the need to inspect System.getProperty("os.name"). Relying on File.separator or Paths.get() ensures correctness across JVM-supported platforms—including Windows, Linux, macOS, and others—with out conditional logic or hardcoded strings.