繁体   English   中英

Java jar无法从Jar中读取文件,只能读取外部文件夹?

[英]Java jar not reading files from the jar, only external folders?

每当我制作一个JAR时,JAR都不会读取其中的文件夹,而只会读取JAR文件夹中的文件夹。 好,那不是很描述。 这是我编辑支持的照片。 在此处输入图片说明

希望您现在就明白。 那么我该如何解决呢? 我已经在Eclipse中的构建路径中使用了res和stats部分,现在该怎么办?

我用来阅读资源的代码:

Image player; player = new ImageIcon("res/player.png").getImage();

使用ImageIcon并将其传递给String ,它期望参数引用File

JavaDocs

从指定的文件创建一个ImageIcon。 ...指定的字符串可以是文件名或文件路径

文件和“资源”是不同的东西。

相反,请尝试使用更多类似...

new ImageIcon(getClass().getResource("res/player.png"));

假设res/player.png位于res目录旁边的jar中。

根据与尝试加载资源的类的关系以及资源的位置,您可能需要使用

new ImageIcon(getClass().getResource("/res/player.png"));

代替...

更新

正如EJP所指出的,一些建议应该为可能找不到该资源做好准备。

URL url = getClass().getResource("/res/player.png");
ImageIcon img = null;
if (url != null) {
    img = new ImageIcon(url);
}
// Deal with null result...

而且您应该使用ImageIO.read读取图像。 除了它支持更多(并且将来可以支持更多)图像格式的事实外,它还可以在返回之前加载图像并在无法读取图像时抛出IOException

URL url = getClass().getResource("/res/player.png");
ImageIcon icon = null;
if (url != null) {
    try {
        BufferedImage img = ImageIO.read(url);
        icon = new ImageIcon(img);
    } catch (IOException exp) {
        // handle the exception...
        exp.printStackTrace();
    }
}
// Deal with null result...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM