I need to construct a file path inside a java program. Which path separator should I use to
allow my program to work on both Windows and Unix?
Keep in mind that Windows needs a drive letter.
You can use Java's File.separator
for system independence.
separator
is a static String
member of the File class.
Here's an example and here's the javadoc for File
.
EDIT - Getting the OS info
If you only want to see wether you should add a the C:
, have a look at this example for getting the OS info, then parse the OS string and see whether it's MS Windows.
You may also find question 1298310 useful for getting all drive information.
Use File.separator
to be platform independent although forward slash /
works on both windows and unix.
Moreover I'd suggest you to avoid using File.separator
. If you want to create file in folder do the following:
File dir = new File("myfolder"); // no slashes
File file = new File(dir, "myfile.txt"); // no slashes.
Use File.listRoots()
to get all driver letters on Windows or single file root /
on Unix.
You should use java.io.File.separator -> http://docs.oracle.com/javase/1.4.2/docs/api/java/io/File.html#separator