简体   繁体   English

Java getResource无法在.jar文件中工作

[英]Java getResource not working in a .jar file

i am trying to export a pacman game i made from eclipse to a .jar package. 我正在尝试将我从eclipse制作的pacman游戏导出到.jar包中。 The problem is that while everything runs fine on eclipse, when the .jar is exported, the resources i use dont load properly. 问题是虽然在eclipse上一切运行正常,但是当导出.jar时,我使用的资源没有正确加载。 I have them in a separate /res folder , which is on the build path. 我把它们放在一个单独的/ res文件夹中 ,它位于构建路径上。 I access them in the following ways: 我通过以下方式访问它们:

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());

What am i doing wrong? 我究竟做错了什么? here is an example of the errors i get(only in the exported .jar on eclipse it runs fine) 这里是我得到的错误的一个例子(仅在eclipse上导出的.jar中运行正常)

In order to retrieve resources from placed inside a jar, you need to use getResourceAsStream() . 为了从jar中放置资源,您需要使用getResourceAsStream()

It works on eclipse because the runtime environment is executed using the "unpacked" JAR ( or better put - prepacked ) using actual files. 它适用于eclipse,因为使用实际文件使用“解压缩”JAR(或更好的put-prepacked)执行运行时环境。

When working with resources, you should always have them as streams and not as files (unless you're trying to do something really weird). 使用资源时,应始终将它们作为流而不是文件(除非您尝试做一些非常奇怪的事情)。

try the following: 尝试以下方法:

ImageIO.read(classLoader.getResourceAsStream("images/PM0.gif"))

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

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