Reputation: 830
I wanted the url of a resource in the following form
C:/Users/.../build/classes/jam/lena1.png
To achieve this I wrote the following code
System.out.println(getClass().getResource("lena1.png").getPath());
but it returns
/C:/Users/.../build/classes/jam/lena1.png
Why is the extra forward slash appearing before the url?
Upvotes: 4
Views: 2450
Reputation: 310913
Because it's a URL, not a filename.
The question itself is odd. What do you care what the path of the URL is?
Upvotes: 1
Reputation: 8793
Regard that Class.getResource() returns a URL, and URLs are not only file paths: A URL involves a protocol, a host, a port, and a path. And it has its own notation and format.
What you are getting in your example is the path part of the URL, and the path always starts by a slash, according to RFC2396.
If you want to get a File from a URL, you could use new File(url.toURI())
... assumming that the input URL is actually referencing a local file path.
Upvotes: 5
Reputation: 2539
use this
String s = (getClass().getResource("lena1.png").getPath()).substring(1);
System.out.println(s);
Upvotes: -1
Reputation: 255
Leading slash to denote the root of the classpath. Try this : System.out.println(getClass().getResource("/lena1.png").getPath());
Upvotes: -1