views:

114

answers:

6

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

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

A: 

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.

Steven Ourada
+4  A: 

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.

jjnguy
+3  A: 

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.

Colin Hebert
pathSeparator will retrieve the platform specific separator between paths ( ';' for unix ':' for windows). I think separator is more appropriate in this case.
Jeroen Rosenberg
pathSeparator is the separator for different entries in the PATH environment variable. For the question, File.separator would be the correct choice.
Thomas Lötzer
Hum you're right the link is wrong but the answer was right.
Colin Hebert
+1  A: 

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

Jeroen Rosenberg
A: 

Personally, I like to use the Path class from Eclipse for handling paths in general, which you can just use standalone with few modifications as it's quite isolated.

http://grepcode.com/file/repository.grepcode.com/java/eclipse.org/3.5/org.eclipse.equinox/common/3.5.0/org/eclipse/core/runtime/Path.java/?v=source

Chris Dennett
+1  A: 

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

EJP