读取Jar中的文件(ZipInputStream等)

我正在用java编写一个游戏,并且所有工作都或多或少都正常,正如您在编码时所期望的那样,但我遇到的一个问题是将图像和声音文件读入游戏。 我编写了一个在Eclipse中运行良好的方法,但是一旦我尝试在可运行的jar中测试它(使用Eclipse导出),我的游戏就会卡在加载屏幕上,因为它无法读取文件。 我意识到你不能在Jar中创建File对象的问题,你必须使用流。 这可能有效,但图像/声音位于文件夹中,我不太确定如何使用流读取文件夹中的文件(即不知道文件的数量)。 因此我尝试使用ZipInputStream重写该方法(我在发布此解决方案之前找到了解决方案时的建议)。 这就是现在的方法:

imageMap = new HashMap(); String imagebase = "/images"; CodeSource src = PlatformerCanvas.class.getProtectionDomain().getCodeSource(); if(src != null) { URL jar = src.getLocation(); try { ZipArchiveInputStream zip = new ZipArchiveInputStream(jar.openStream()); ZipArchiveEntry ze = null; while((ze = zip.getNextZipEntry()) != null) { System.out.println(ze.getName()); if(ze.getName().startsWith(imagebase) && ze.getName().endsWith(".png")) { loading++; imageMap.put(ze.getName().replaceAll(imagebase + "/", ""), ImageIO.read(this.getClass().getResource(ze.getName()))); } } zip.close(); System.out.println("Finished Loading Images"); } catch (IOException e) { e.printStackTrace(); } } 

但是,这完全跳过了while循环,因为getNextZipEntry返回null。 我尝试使用基本的Zip归档库,但是有人推荐了Apache Commons库,但都没有用。 我的Jar设置如下:

 Jar /game/gameClasses /images/imageFiles /sounds/soundFiles /whateverOtherFoldersEclipseCreated 

所以我的问题是:为什么这个当前的方法不起作用,我该如何解决它? 或者,如何以不同的方式加载图像/声音? 我看了很多其他问题并尝试过很多不同的东西,但没有一个对我有用。

或者,如何以不同的方式加载图像/声音?

一种常见的技术是在Jar中的已知位置包括资源列表。 读取列表,然后迭代行(假设每个资源一行)并读取那条路径。