Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Java utility which will convert a String path to use the correct File separator char?

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?

like image 899
Grundlefleck Avatar asked Nov 08 '09 17:11

Grundlefleck


People also ask

How do you get the path of the file in the file Java?

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.

What is separator char in Java?

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.

What is path separator in Java?

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.

What is a file separator in Java?

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.


1 Answers

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.

like image 122
Brian Agnew Avatar answered Sep 21 '22 16:09

Brian Agnew