Platform independent paths in Java

I know the relative path of a file and want to handle it as a File object on both Linux and Windows.

What is the best way to specify platform-independent paths in Java?


Just use /. I've been using it for 23.5 years. Never a problem.


The File class contains the following public members that you can use for platform specific file paths:

static String pathSeparator:
The system-dependent path-separator character, represented as a string for convenience.
static char pathSeparatorChar:
The system-dependent path-separator character.
static String separator:
The system-dependent default name-separator character, represented as a string for convenience. static char separatorChar:
The system-dependent default name-separator character.


You can use any path separator in Java, it will work on both Unix and Windows. If you still want to use the system path separator there is the File.separator property which will give you the right one depending on the current system.

For the root, you can use listRoots() which gives you an array of root, there will be only one element on Unix systems, and as many as you have drives on Windows.


You can use the static field File.separator to retrieve the platform specific separator character for file paths


Java is pretty smart about paths in File objects. I just use something like "../foo/bar" and it works in those two platforms plus MacOSX.