Loading resources (images) contained in a .Jar file or in the classpath

前端 未结 1 716
你的背包
你的背包 2020-12-06 08:51

So I\'ve tried various reading various fixes for this problem on stack exchange most say to use getResourceAsStream() method, which I have done. This is my Reso

相关标签:
1条回答
  • 2020-12-06 09:29

    The question of how to load classpath resources is quite recurring, and a bit confusing for a Java newbie: some answers suggest class.getClassLoader().getResourceAsStream, others class.getResourceAsStream, although they have a slight different semantic:

    1. class.getResourceAsStream does a path translation
    2. class.getClassLoader().getResourceAsStream does not translate the path

    For better show the difference, I'm going to propose the following test class, which in 4 different ways try to load the same resource (an image), only 2 working depending on the used path. The Jar content-tree is:

    enter image description here

    The class:

    package image;
    
    import java.io.InputStream;
    
    public class ImageLoader {
        public static void main(String[] args ){
            String cmd = null;
            InputStream is = null;
            final String image = "save.png";
    
            if("test1".equals(args[0])){
                cmd = "ImageLoader.class.getClassLoader().getResourceAsStream(\""+image+"\")";
                is = ImageLoader.class.getClassLoader().getResourceAsStream(image);     //YES, FOUND
    
    
            }else if("test2".equals(args[0])){
                cmd = "ImageLoader.class.getResourceAsStream(\""+image+"\")";
                is = ImageLoader.class.getResourceAsStream(image);                      //NOT FOUND
    
            }else if("test3".equals(args[0])){
                cmd = "ImageLoader.class.getResourceAsStream(\"/"+image+"\")";
                is = ImageLoader.class.getResourceAsStream("/"+image);                  //YES, FOUND
    
            }else if("test4".equals(args[0])){
                cmd = "ImageLoader.class.getClassLoader().getResourceAsStream(\"/"+image+"\")";
                is = ImageLoader.class.getClassLoader().getResourceAsStream("/"+image); //NOT FOUND
    
            }else {
                cmd = " ? ";
            }
    
            System.out.println("With "+cmd+", stream loaded: "+(is != null));
        }
    }
    

    Run with:

    java -cp resLoader.jar image.ImageLoader test4

    Hope this class can help in understanding the different behaviour.

    0 讨论(0)
提交回复
热议问题