Question

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?

Was it helpful?

Solution 2

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);

OTHER TIPS

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();

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

URL res = this.getClass().getClassLoader().getResource(dictionaryPath);
String path = Paths.get(res.toURI()).toString();

You could probably just format the string once you get it.

something like this:

path2= path2[1:];

I was searching for one-line solution, so the best what i came up with was deleting it manually like this:

String url = this.getClass().getClassLoader().getResource(dictionaryPath).getPath().replaceFirst("/","");

In case if someone also needs to have it on different OS, you can make IF statement with

System.getProperty("os.name");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top