Java 如何访问JAR文件中的资源?
我有一个带有工具栏的Java项目,工具栏上有图标。这些图标存储在名为resources/的文件夹中,因此,例如,路径可能是“resources/icon1.png”。该文件夹位于我的src目录中,因此在编译该文件夹时会将其复制到bin中/ 我正在使用以下代码访问资源Java 如何访问JAR文件中的资源?,java,image,url,resources,jar,Java,Image,Url,Resources,Jar,我有一个带有工具栏的Java项目,工具栏上有图标。这些图标存储在名为resources/的文件夹中,因此,例如,路径可能是“resources/icon1.png”。该文件夹位于我的src目录中,因此在编译该文件夹时会将其复制到bin中/ 我正在使用以下代码访问资源 protected AbstractButton makeToolbarButton(String imageName, String actionCommand, String toolTipText, S
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时,找不到图标
我打开了JAR文件,资源文件夹就在那里。我尝试了一切,移动文件夹,修改JAR文件等等,但我无法让图标显示出来
有人知道我做错了什么吗
(作为一个附带问题,是否有任何文件监视器可以处理JAR文件?当出现路径问题时,我通常只打开FileMon来查看发生了什么,但在本例中,它只是显示为访问JAR文件)
谢谢。我发现您的代码有两个问题:
getClass().getResourceAsStream(imgLocation);
这假定映像文件与此代码所属类的.class文件位于同一文件夹中,而不是位于单独的资源文件夹中。请尝试以下方法:
getClass().getClassLoader().getResourceAsStream("resources/"+imgLocation);
另一个问题:
byte abyte0[] = new byte[imageStream.available()];
方法InputStream.available()
不返回流中的总字节数!它返回没有阻塞的可用字节数,通常更少
您必须编写一个循环,将字节复制到临时
ByteArrayOutputStream
,直到到达流的末尾。或者,使用getResource()
和接受URL参数的createImage()
方法。Swing教程中的部分向您展示了如何创建URL并在两条语句中读取图标。要从JAR资源加载图像,请使用以下代码:
Toolkit tk = Toolkit.getDefaultToolkit();
URL url = getClass().getResource("path/to/img.png");
Image img = tk.createImage(url);
tk.prepareImage(img, -1, -1, null);
例如,在NetBeans项目中,在src文件夹中创建一个resources文件夹。把你的图片(jpg,…)放在那里 无论使用ImageIO还是Toolkit(包括getResource),都必须在图像文件的路径中包含前导/
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/resources/agfa_icon.jpg"));
setIconImage(image);
如果此代码在JFrame类中,则图像将作为标题栏中的图标添加到框架中。该工具包包含哪些软件包?