开发者

Referencing an image in a .jar file

开发者 https://www.devze.com 2023-03-13 05:18 出处:网络
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 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开发者_StackOverflow.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?


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.


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


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.


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消