4

我的第一个问题:

几天来我一直试图弄清楚这一点,但我到了失去耐心的地步。以下是一些代码和我的项目结构。

问题:我怎样才能getResources()在 eclipse 中工作并在被导入 jar 之后?

谢谢您的帮助。

public enum Icons {
    XXX("src/resoruces/icons/xyz.png");
    private ImageIcon icon;
    Icons(String path) {
       try {
           // will fail miserably in eclipse and after exporting to jar
           URL imageURL = getClass().getClassLoader().getResource(path);
           icon = new ImageIcon(imageURL);
       } catch (Exception e) {
           // works like a char in eclipse and after creating the jar file
           // with the files in the same directory
           System.out.println("getResoruce() did not work");
           icon = new ImageIcon(path);
       }
   }

项目结构

4

3 回答 3

11

通常从 Eclipse 导出 JAR 文件时,导出的内容src/resources减去路径src本身。要从您的 JAR 中加载图像,您可以执行以下操作:

InputStream stream = getClass().getResourceAsStream("/resources/icons/xyz.png");
ImageIcon icon= new ImageIcon(ImageIO.read(stream));

确定的一种方法是检查:

jar tvf yourjar.jar
于 2012-12-31T19:01:26.140 回答
3

如果 png 文件已打包到 JAR 中与它们在原始 src 目录中相同的位置,则

XXX("resources/icons/xyz.png");

应该产生正确的结果。

于 2012-12-31T18:25:00.127 回答
1

src目录在类路径中不可用

InputStream imageInputStream = getClass().getClassLoader().getResourceAsStream("resources/icons/xyz.png");
byte[] imageData = org.apache.commons.io.IOUtils.toByteArray(in)

ImageIcon imageIcon = new ImageIcon(imageData, "description about image");
于 2012-12-31T18:17:19.347 回答