如何访问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文件)


 

第 1 个答案:

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

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

 

第 2 个答案:

我发现你的代码有两个问题:

getClass().getResourceAsStream(imgLocation);

这假定图像文件与该代码所属类的.class文件位于同一文件夹中,而不是在单独的资源文件夹中。尝试以下方法:

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

另一个问题:

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

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

你必须编写一个循环以将字节复制到临时文件,ByteArrayOutputStream直到到达流的末尾。或者,使用getResource()createImage()接受URL参数的方法。


我有一个另存为的图像byte[],我想在JasperReport中将其显示为图像。我尝试从Java方法获取数据:public InputStream getImage(){ r ...