简体   繁体   English

引用 a.jar 文件中的图像

[英]Referencing an image in a .jar file

I am having real trouble referencing a simple image in a jar file.我在引用 jar 文件中的简单图像时遇到了真正的麻烦。

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 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()在我的 java 文件中,我引用了这样的图像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在首次亮相中,它看起来像这样/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. windows 的前导“/”和分隔符不正确是什么意思。

I checked this path and it does not work in MS Explorer.我检查了这个路径,它在 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?好的,它在某种程度上可以工作,除了图像路径不正确,/C: /C:/Documents%20and%20Settings/myname/workspace/gnupdf/bin/au/com/mysite/pdf/res/logo.png不是引用文件,前导斜杠和 %20 空格字符是什么? How do I convert this into a file URL instead of a web url?如何将其转换为文件 URL 而不是 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:我无法告诉您为什么这不起作用,但是当我参考存储在 jar 中的图像时,通常用于菜单图标图像,我使用:

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.如果图像位于 jar 中,则 getResource 不会返回任何有用的信息。 getResourceAsStream is probably what you want. getResourceAsStream 可能是您想要的。

Using getResource from a.jar will work.使用来自 a.jar 的 getResource 将起作用。 A couple things: What's the Class-Path of your.jar file's Manifest?有几件事:您的.jar 文件清单的类路径是什么? Files inside of a.jar are case sensitive. a.jar 中的文件区分大小写。

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.然后您可以在 java 程序中使用您的图像。

See this for instance:例如看这个:

How do I list the files inside a JAR file? 如何列出 JAR 文件中的文件?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM