4

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?

2
  • if System.out.println(getClass().getResource("lena1.png").toString()); is written then output is : file:/C:/Users/.../build/classes/jam/lena1.png Commented Oct 11, 2014 at 10:32
  • I'm getting the resource, but the method getPath() returns the URL with an additional forward slash Commented Oct 11, 2014 at 10:41

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for your suggestion, but url.toURI() doesn't work, it gives the same result.
I insist: First, get a URI from the URL with url.toURI(), then create a File object passing the URI as a parameter. Then, if you want the absolute local path, you can get it with file.getAbsolutePath().
but there is a little problem, tthis method returns path with back slash
If you're running your program on a Windows plattform, the correct path separator is the back slash. Is it a problem for you? Realise that the value returned by file.getAbsolutePath() is a valid path.
Yes, its a valid path but in java if the path has backslash it should be something like "C:\\Users\\..." but instead it is like "C:\Users\..."
|
1

Because it's a URL, not a filename.

The question itself is odd. What do you care what the path of the URL is?

1 Comment

I need the path for using it in an external library.
-1

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

1 Comment

The root of the CLASSPATH isn't C:/, and your suggested code isn't correct either: it should be "/jam/lena1.png".
-1

use this

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

1 Comment

This will remove the slash, but doesn't not clarify why it is there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.