如何访问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;
}
(imageName将是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屋!