10

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?

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Ev0oD
  • 1,395
  • 16
  • 33

5 Answers5

10

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();
Sundae
  • 724
  • 1
  • 8
  • 27
4

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);
David Jashi
  • 4,490
  • 1
  • 21
  • 26
2

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

URL res = this.getClass().getClassLoader().getResource(dictionaryPath);
String path = Paths.get(res.toURI()).toString();
Toper
  • 114
  • 7
0

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

something like this:

path2= path2[1:];

Akshay
  • 783
  • 6
  • 20
  • Did you read the first three lines of this post? I am using it - I can not and do not want to use it since this attitude is not working on other than windows machine. + I believe there must exist a more elegant solution than this. – Ev0oD Jul 05 '13 at 13:23
0

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