I have developed a number of classes which manipulate files in Java. I am working on a Linux box, and have been blissfully typing new File("path/to/some/file");
. When it came time to commit I realised some of the other developers on the project are using Windows. I would now like to call a method which can take in a String of the form "/path/to/some/file"
and, depending on the OS, return a correctly separated path.
For example:
"path/to/some/file"
becomes "path\\to\\some\\file"
on Windows.
On Linux it just returns the given String.
I realise it wouldn't take long to knock up a regular expression that could do this, but I'm not looking to reinvent the wheel, and would prefer a properly tested solution. It would be nice if it was built in to the JDK, but if it's part of some small F/OSS library that's fine too.
So 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.