如何访问JAR文件中的资源?

我有一个带有工具栏的Java项目,工具栏上有图标。 这些图标存储在名为resources /的文件夹中,因此例如路径可能是“resources / icon1.png”。 这个文件夹位于我的src目录中,所以编译时将文件夹复制到bin /

我正在使用以下代码来访问资源。

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时,找不到图标。

我打开了JAR文件,资源文件夹就在那里。 我已经尝试了一切,移动文件夹,更改JAR文件等,但我无法显示图标。

有谁知道我做错了什么?

(作为一个附带问题,是否有任何文件监视器可以使用JAR文件?当出现路径问题时,我通常只是打开FileMon来查看发生了什么,但它只是在这种情况下显示为访问JAR文件)

谢谢。

要从JAR资源加载图像,请使用以下代码:

 Toolkit tk = Toolkit.getDefaultToolkit(); URL url = getClass().getResource("path/to/img.png"); Image img = tk.createImage(url); tk.prepareImage(img, -1, -1, null); 

我看到你的代码有两个问题:

 getClass().getResourceAsStream(imgLocation); 

这假设图像文件与此代码所在类的.class文件位于同一文件夹中,而不是位于单独的资源文件夹中。 试试这个:

 getClass().getClassLoader().getResourceAsStream("resources/"+imgLocation); 

另一个问题:

 byte abyte0[] = new byte[imageStream.available()]; 

方法InputStream.available()不返回流中的总字节数! 它返回没有阻塞的可用字节数,这通常要少得多。

您必须编写一个循环来将字节复制到临时的ByteArrayOutputStream直到到达流的末尾。 或者,使用getResource()和带有URL参数的createImage()方法。

Swing教程中有关如何使用图标的部分介绍了如何创建URL并在两个语句中读取Icon。

例如,在NetBeans项目中,在src文件夹中创建资源文件夹。 把你的图像(jpg,…)放在那里。

无论您使用ImageIO还是Toolkit(包括getResource),都必须在图像文件的路径中包含一个前导/:

 Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/resources/agfa_icon.jpg")); setIconImage(image); 

如果此代码位于JFrame类中,则图像将作为标题栏中的图标添加到框架中。