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?
In Java, for NIO Path, we can use path. toAbsolutePath() to get the file path; For legacy IO File, we can use file. getAbsolutePath() to get the file path.
separator: Platform dependent default name-separator character as String. For windows, it's '\' and for unix it's '/'. File. separatorChar: Same as separator but it's char.
For file path or directory separator, the Unix system introduced the slash character / as directory separator, and the Microsoft Windows introduced backslash character \ as the directory separator. In a nutshell, this is / on UNIX and \ on Windows.
A file separator is a character that is used to separate directory names that make up a path to a particular location. This character is operating system specific.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With