Getting images from a .jar file

前端 未结 2 1094
鱼传尺愫
鱼传尺愫 2020-12-04 00:13

I need to get res folder to compile when I export a executable jar file in eclipse also when I use the getClass().getResource() method it doesn\'t work.

相关标签:
2条回答
  • 2020-12-04 00:54

    Either:

    • your path is wrong, you should get an error message if so, check it to see what path it actually tries, might not be what you think. Or debug and see what path it tries or even just print the path it tries.

    or

    • it's not in the jar. Check the jar file with a zip-program and/or rename it to have zip in the and open it to check that the file is really there.
    0 讨论(0)
  • 2020-12-04 00:55

    I have now fixed the problem - this is the code that works

     public BufferedImage loadImage(String fileName){
    
        BufferedImage buff = null;
        try {
            buff = ImageIO.read(getClass().getResourceAsStream(fileName));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        return buff;
    
    }
    

    The value of fileName is just an image name eg BufferedImage img = loadImage("background.png");

    Thank you all for your help.

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