如何访问 JAR 文件中的资源? [英] How to access resources in JAR file?
问题描述
我有一个带有工具栏的 Java 项目,工具栏上有图标.这些图标存储在名为 resources/的文件夹中,因此例如路径可能是resources/icon1.png".该文件夹位于我的 src 目录中,因此编译时将该文件夹复制到 bin/
I have a Java project with a toolbar, and the toolbar has icons on it. These icons are stored in a folder called resources/, so for example the path might be "resources/icon1.png". This folder is located in my src directory, so when it is compiled the folder is copied into bin/
我正在使用以下代码访问资源.
I'm using the following code to access the resources.
protected AbstractButton makeToolbarButton(String imageName, String actionCommand, String toolTipText,
String altText, boolean toggleButton) {
String imgLocation = imageName;
InputStream imageStream = getClass().getResourceAsStream(imgLocation);
AbstractButton button;
if (toggleButton)
button = new JToggleButton();
else
button = new JButton();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(listenerClass);
if (imageStream != null) { // image found
try {
byte abyte0[] = new byte[imageStream.available()];
imageStream.read(abyte0);
(button).setIcon(new ImageIcon(Toolkit.getDefaultToolkit().createImage(abyte0)));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
imageStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else { // no image found
(button).setText(altText);
System.err.println("Resource not found: " + imgLocation);
}
return button;
}
(图像名称将是resources/icon1.png"等).这在 Eclipse 中运行时工作正常.但是,当我从 Eclipse 导出可运行的 JAR 时,找不到图标.
(imageName will be "resources/icon1.png" etc). This works fine when run in Eclipse. However, when I export a runnable JAR from Eclipse, the icons are not found.
我打开了 JAR 文件,资源文件夹在那里.我已经尝试了所有方法,移动文件夹,更改 JAR 文件等,但我无法显示图标.
I opened the JAR file and the resources folder is there. I've tried everything, moving the folder, altering the JAR file etc, but I cannot get the icons to show up.
有人知道我做错了什么吗?
Does anyone know what I'm doing wrong?
(作为一个附带问题,有没有可以处理 JAR 文件的文件监视器?出现路径问题时,我通常只是打开 FileMon 来查看发生了什么,但在这种情况下它只是显示为访问 JAR 文件)
(As a side question, is there any file monitor that can work with JAR files? When path problems arise I usually just open FileMon to see what's going on, but it just shows up as accessing the JAR file in this case)
谢谢.
推荐答案
要从 JAR 资源加载图像,请使用以下代码:
To load an image from a JAR resource use the following code:
Toolkit tk = Toolkit.getDefaultToolkit();
URL url = getClass().getResource("path/to/img.png");
Image img = tk.createImage(url);
tk.prepareImage(img, -1, -1, null);
这篇关于如何访问 JAR 文件中的资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!