I want to take a string that represents a path and convert it to an absolute Unix-style path. This string could be in either Windows or Unix styles, as it's the result of a call to MainClass.class.getClassLoader().getResource("").getPath()
, which returns different style paths depending on your system.
(I'm doing this for a game I'm writing, a portion of which gives the user a simple "bash-ish" shell, and I want the user to be able to read files. The fake filesystem is stored as a normal directory tree in a subdirectory of my project. This filesystem is going to use Unix-style paths, and I want to be able to concatenate inputted paths with the aforementioned string (with some minor edits to get it into the right directory) so I can find the contents of the files.)
Any ideas how I might go about doing this? I've tried a number of things, but I can't seem to get it to work properly on my friend's Windows 7 system.
At the moment I'm just using a simple thing that checks to see if the string starts with "C: \" or something similar and then replaces backslashes with slashes, but there's no way that that can be a good way to go about this, and I'm sure other people have faced the problem of different path styles before. It's certainly a very temporary solution.
In general, I never had problems on any operating system with using a '/' as separator.
new File("/a/b/c.txt");
works at least on Unix, Windows and iSeries.
If you want to be correct, there's a constant 'File.separator', that holds the operating systems separator.
If you want to replace the backslash '\' in a string, remember that it is a special escape character:
String newString = str.replace("\\","/");
edit:
and remember, String is immutable.
str.replace("\\","/");
will not change the string, only return a new string with the replaced characters.
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