Convert a Windows-style path to a Unix path

I want to take a string representing a path and convert it to an absolute Unix-style path. This line can be in Windows or Unix styles, as this is the result of calling MainClass.class.getClassLoader().getResource("").getPath() , which returns different styles paths depending on your system.

(I do this for the game I am writing, the part of which gives the user a simple bash -ish shell, "and I want the user to read files. The fake file system is stored as a normal directory tree in a subdirectory of my project. This file system will use Unix-style paths, and I want to be able to concatenate the entered paths with the above line (with some minor changes to get it to the right of the directory), so I can find the contents of the files.)

Any ideas how I can do this? I tried several things, but I can not get it to work correctly on my Windows 7 system.

Right now, I'm just using a simple thing that checks if a line starts with "C: \" or something similar, and then replaces the backslash with a slash, but there is no way that this is a good way to go about it, and I am sure that other people have encountered the problem of different styles of the way before. This is certainly a very temporary solution.

+4
source share
2 answers

In general, I have never had a problem on any operating system using the delimiter '/'.

  new File("/a/b/c.txt"); 

works at least on Unix, Windows, and iSeries.

If you want to be true, there is a permanent "File.separator" that contains the operating system separator.

If you want to replace the backslash '\' in a string, remember that this is a special escape character:

 String newString = str.replace("\\","/"); 

change

and remember that String is immutable.

  str.replace("\\","/"); 

will not change the line, will only return a new line with replaced characters.

+13
source

If all you want to do is access the file with a relative name in a specific directory, you can simply use the regular File API, for example:

 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 styling (I just say this from my own experience).

0
source

Source: https://habr.com/ru/post/1445278/


All Articles