How to get rid of a starting slash in a URI or URL?

I use

URL res = this.getClass().getClassLoader().getResource(dictionaryPath); String path = res.getPath(); String path2 = path.substring(1); 

because the output of the getPath () method returns sth as follows:

  /C:/Users/...... 

and i need it

  C:/Users.... 

I really need the address below, because some external library refuses to work with a slash at the beginning or with a file: / at the beginning or something else.

I tried almost all the methods in the URL, for example toString () toExternalPath (), etc. and did the same with the URI, and not one of them returned it as I needed it. (I totally don’t understand why it keeps a slash in the beginning).

It is ok to do this on my machine, just erasing the first char. But a friend tried to run it on linux, and since the addresses are different there, it does not work ...

What should be with such a problem?

+4
source share
3 answers

While UNIX paths should not contain drive letters, you can try the following:

 URL res = this.getClass().getClassLoader().getResource(dictionaryPath); String path = res.getPath(); char a_char = text.charAt(2); if (a_char==':') path = path.substring(1); 
+2
source

Convert the URL to a URI and use it in the file constructor:

 URL res = this.getClass().getClassLoader().getResource(dictionaryPath); File file = new File(res.toURI()); String fileName = file.getPath(); 
+4
source

Perhaps you can just format the string after receiving it.

something like that:

path2 = path2 [1:];

+1
source

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


All Articles