Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using

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

because the output of the method getPath() returns sth like this:

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

and I need this

 C:/Users....

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

I tried pretty much all the methods in URL like toString() toExternalPath() etc. and done the same with URI and none of it returns it like I need it. (I totally don't understand, why it keeps the slash at the beginning).

It is okay to do it on my machine with 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 with such problem?

like image 242
Ev0oD Avatar asked Jul 05 '13 13:07

Ev0oD


3 Answers

Convert to a URI, then use Paths.get().

URL res = this.getClass().getClassLoader().getResource(dictionaryPath);
String path = Paths.get(res.toURI()).toString();
like image 175
Toper Avatar answered Oct 06 '22 00:10

Toper


Convert the URL to a URI and use that in the File constructor:

URL res = this.getClass().getClassLoader().getResource(dictionaryPath);
File file = new File(res.toURI());
String fileName = file.getPath();
like image 22
Sundae Avatar answered Oct 06 '22 00:10

Sundae


As long as UNIX paths are not supposed to contain drive letters, you may try this:

URL res = this.getClass().getClassLoader().getResource(dictionaryPath);
String path = res.getPath();
char a_char = text.charAt(2);
if (a_char==':') path = path.substring(1);
like image 33
David Jashi Avatar answered Oct 06 '22 01:10

David Jashi