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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With