getResourceAsStream() returning null in jar but fi

2019-01-28 07:53发布

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 before, I know, but I don't seem to get an answer that works. Any help here? Thanks in advance!

The thing that seems to be having the problem is the class TextureHelper:

public class TextureHelper {

    public static Texture LoadTexture(String texture)
    {
        try {
            return TextureLoader.getTexture("PNG", ResPlaceholder.class.getResourceAsStream(texture));
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}

Some notes:

I've also tried "/res/" + texture, as well as many other things like it.

ResPlaceholder is a class that sits in the res folder where I store all my images. It's a blank empty class.

This works perfectly in Eclipse.

My jar has these folders (just as an example):

foo.jar

----core

--------TextureLoader

----res

-------- Assorted Image Files

-------- ResPlaceholder

This is the same as the packages in eclipse.

Any help you have would be appreciated, I've been stuck on this for days with no progress.

EDIT:

META-INF/MANIFEST.MF

Main.class config/

config/Images.class

core/

core/LevelLoader.class

core/TextureHelper.class

core/TileSet.class

-Skipping some other stuff that has nothing to do with this-

res/

res/ResPlaceholder.class

res/BlankImg.png

res/test.txt

res/testImg.png

res/testTiles.png

1条回答
姐就是有狂的资本
2楼-- · 2019-01-28 08:18

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.

查看更多
登录 后发表回答