KiKMak
KiKMak

Reputation: 830

Java getResource() unexpected path

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

Answers (4)

user207421
user207421

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

Little Santi
Little Santi

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

govindpatel
govindpatel

Reputation: 2539

use this

String s = (getClass().getResource("lena1.png").getPath()).substring(1);
System.out.println(s);

Upvotes: -1

iColdBeZero
iColdBeZero

Reputation: 255

Leading slash to denote the root of the classpath. Try this : System.out.println(getClass().getResource("/lena1.png").getPath());

Upvotes: -1

Related Questions