我正在尝试将我从 eclipse 制作的 pacman 游戏导出到 .jar 包。问题是,虽然在 eclipse 上一切运行良好,但当导出 .jar 时,我使用的资源无法正确加载。我把它们放在一个单独的 /res folder 中,它在构建路径上。我通过以下方式访问它们:
ClassLoader classLoader = getClass().getClassLoader();
try{
image = ImageIO.read(new File(classLoader.getResource("images/PM0.gif").getFile()));
}
catch (IOException e1) {
e1.printStackTrace();
}
File file = new File(classLoader.getResource("levels/"+fileName).getFile());
我做错了什么? here是我得到的错误示例(仅在 eclipse 上导出的 .jar 中运行良好)
最佳答案
在使用资源时,您应该始终将它们作为流而不是文件(除非您正在尝试做一些非常奇怪的事情)。
尝试以下操作:
ImageIO.read(classLoader.getResourceAsStream("images/PM0.gif"))
关于Java getResource 不能在 .jar 文件中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42728973/