Is there a Java utility which will convert a String path to use the correct File separator char?
Apache Commons
comes to the rescue (again). The Commons IO
method FilenameUtils.separatorsToSystem(String path)
will do what you want.
Needless to say, Apache Commons IO
will do a lot more besides and is worth looking at.
A "/path/to/some/file"
actually works under Windows Vista and XP.
new java.io.File("/path/to/some/file").getAbsoluteFile()
> C:\path\to\some\file
But it is still not portable as Windows has multiple roots. So the root directory has to be selected in some way. There should be no problem with relative paths.
Edit:
Apache commons io does not help with envs other than unix & windows. Apache io source code:
public static String separatorsToSystem(String path) {
if (path == null) {
return null;
}
if (isSystemWindows()) {
return separatorsToWindows(path);
} else {
return separatorsToUnix(path);
}
}
This is what Apache commons-io does, unrolled into a couple of lines of code:
String separatorsToSystem(String res) {
if (res==null) return null;
if (File.separatorChar=='\\') {
// From Windows to Linux/Mac
return res.replace('/', File.separatorChar);
} else {
// From Linux/Mac to Windows
return res.replace('\\', File.separatorChar);
}
}
So if you want to avoid the extra dependency, just use that.