Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java getResource() unexpected path

Tags:

java

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?

like image 623
KiKMak Avatar asked Oct 19 '25 03:10

KiKMak


1 Answers

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.

like image 182
Little Santi Avatar answered Oct 21 '25 17:10

Little Santi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!