In java, how do you retrieve images from a jar file?

↘锁芯ラ 提交于 2019-12-24 04:29:31

问题


I've been having problems exporting my java project to a jar (from Eclipse). There is a file that I've included in the jar named images. It contains all of the image files used by my project. The problem is, my references to those images only work when the project isn't in jar form. I can't figure out why and I'm wondering if I need to change the wording of the image references. This is what I'm doing to reference images:

    URL treeURL = null;
    Image tree = null;
    File pathToTheTree = new File("images/tree.png");
    try {
        treeURL = pathToTheTree.toURL();
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        tree = ImageIO.read(treeURL);
    } catch(IOException e) {
        e.printStackTrace();
    }

Most likely it is a simple problem, as I'm a beginner at coding. What do I need to change to make these references work when it's all in a jar?


回答1:


It is indeed simple: you use the various getResource() methods in java.lang.Class and java.lang.ClassLoader. For example, in your app, you could just write

treeURL = getClass().getResource("/images/tree.png");

This would find the file in an images directory at the root of the jar file. The nice thing about the getResource() methods is that they work whether the files are in a jar or not -- if the images directory is a real directory on disk, this will still work (as long as the parent of images is part of your class path.)



来源:https://stackoverflow.com/questions/10875892/in-java-how-do-you-retrieve-images-from-a-jar-file

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