[英]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
。
从指定的文件创建一个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.