Convert Windows-style path into Unix path [closed]

匿名 (未验证) 提交于 2019-12-03 03:10:03

问题:

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.

回答1:

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.



回答2:

If all you want to do is be able to access a file with a relative name to a certain directory, you can just use plain File API, like this:

final String baseDir = MainClass.class.getClassLoader().getResource("").getPath(); final String relativeName = "audio/abc.mp3"; final File relativeFile = new File(baseDir, relativeName); final String canonicalPath = relativeFile.getCanonicalPath();

It should work on both Unix and Windows, since Windows accepts both Unix- and Windows- style paths (just saying it from my own experience).



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!