0

I am having real trouble referencing a simple image in a jar file.

I have a package au.com.mysite.pdf tha contains the java files I have a package au.com.mysite.pdf.res tha contains images

In my java file I reference an image like this getClass().getResource("/au/com/mysite/pdf/res/logo.png").getPath()

but the image can never be found. In the debutter it looks like this /C:/Documents%20and%20Settings/myname/workspace/gnupdf/bin/au/com/mysite/pdf/res/logo.png

What is with the leading '/' and the separators are not correct for windows.

I checked this path and it does not work in MS Explorer.

UPDATE

Ok, it is working to some extent except the image path is not correct, /C:/Documents%20and%20Settings/myname/workspace/gnupdf/bin/au/com/mysite/pdf/res/logo.png is not a reference to a file, what is with the leading slash and the %20 space characters? How do I convert this into a file URL instead of a web url?

jax
  • 37,735
  • 57
  • 182
  • 278
  • I don't have an answer, but as a general matter Windows handles forward slashes as path separators just fine. – Dan Jun 14 '11 at 23:50
  • 1
    You should also make sure your image really is in the jar in the right directory with `jar tf myjar.jar`. – toto2 Jun 15 '11 at 00:01

4 Answers4

3

I can't tell you why that's not working, but when I reference images I have stored in a jar, typically for menu icon images, I use:

ImageIcon image = new ImageIcon(this.getClass().getResource("/package/sub_package/image_name.png"));

This has always worked for me.

Brandon Buck
  • 7,177
  • 2
  • 30
  • 51
1

If the image is in a jar, getResource is not going to return anything useful. getResourceAsStream is probably what you want.

James Scriven
  • 7,784
  • 1
  • 32
  • 36
  • The API takes a string as the location of the file – jax Jun 15 '11 at 03:46
  • What API are you trying to use? My point is that there is no file, only a bunch of bytes inside the jar. Most apis will allow you to specify the input as a stream rather than a file location, which is what you will need. – James Scriven Jun 15 '11 at 10:31
0

Using getResource from a .jar will work. A couple things: What's the Class-Path of your .jar file's Manifest? Files inside of a .jar are case sensitive.

Jeffrey
  • 44,417
  • 8
  • 90
  • 141
0

update

I saw what your problem might be. You're trying to get the path, but that's not necessary because anyway you won't be able to reference it.

Instead do this:

BufferedImage image = ImageIO.read(this.getClass().getResource("images/image01.png)); 

And then you can use your image within a java program.

See this for instance:

How do I list the files inside a JAR file?

Community
  • 1
  • 1
OscarRyz
  • 196,001
  • 113
  • 385
  • 569