Reading Files Within a Jar(ZipInputStream, etc.) [duplicate]

大兔子大兔子 提交于 2019-12-23 01:12:27

问题


I'm writing a game in java and all is working more or less well, as you would expect when coding, but one issue I have come across is reading the image and sound files into the game. I wrote a method that works really well within Eclipse, but as soon as I try to test it in a runnable jar (exported using Eclipse) my game gets stuck on the loading screen because it can't read the files. I realized the problem there being that you cannot create File objects within a Jar, you have to use streams. This could work, but the images/sounds are located within folders and I'm not very sure how you can read files within a folder with streams(i.e not knowing the amount of files). Because of this I have tried to rewrite the method using the ZipInputStream (I found this as recommended when looking for solutions prior to posting this). This is what the method looks like now:

imageMap = new HashMap<String, BufferedImage>();
    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();
        }
    }

However, this completely skips over the while loop because getNextZipEntry return null. I tried using the base Zip archive libraries, but someone recommended the Apache Commons libraries, but neither worked. My Jar setup is this:

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

So my question is this: Why isn't this current method working and how do I fix it? Or, how can I load the images/sounds in a different way that works? I have looked at many other questions and tried many different things, but none worked for me.


回答1:


Or, how can I load the images/sounds in a different way that works?

One common technique is to include a list of resources in a known location in the Jar. Read the list, then iterate the lines (presuming one line per resource) & read the paths that way.



来源:https://stackoverflow.com/questions/17515757/reading-files-within-a-jarzipinputstream-etc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!