getResourceAsStream() returning null in jar but fine in eclipse

前端 未结 1 1935
孤独总比滥情好
孤独总比滥情好 2020-12-21 02:59

I have a program in Java using LWJGL. It runs fine in Eclipse, but when I try to compile it as a jar file it crashes, giving me a NullPointerException. It\'s been asked befo

1条回答
  •  Happy的楠姐
    2020-12-21 03:24

    If the path String is something like: /res/testImg.png it should work.

    i.e.,

    String resourcePath = "/res/testImg.png";
    InputStream inStream = ResPlaceholder.class.getResourceAsStream(resourcePath );
    BufferedImage img = ImageIO.read(inStream);
    
    // use the img BufferedImage here
    // for example:
    ImageIcon icon = new ImageIcon(img);
    JOptionPane.showMessageDialog(null, icon);
    

    As an aside, it's always good to test problems and check new concepts in small test programs. In your case, I would create a small simple program with just a main method that attempts to extract a jar's image resource and display it in an option pane much like my small code above does. I'd try to avoid long lines and instead separate each step on its own line, again similar to my post above. This way if an exception is thrown, the code on the line will be much more informative as to what is causing the error.

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