Domanda

I want to embed a txt file into runnable jar and read it. I tried using this code

Reader reader = new InputStreamReader(getClass().getResourceAsStream("/src/kan/master_ship.txt"),"UTF-8");

But it gives

java.lang.NullPointerException
    at java.io.Reader.<init>(Unknown Source)
    at java.io.InputStreamReader.<init>(Unknown Source)
    at kan.util.Master.loadMasterShip(Master.java:37)
    at kan.util.Master.load(Master.java:26)
    at kan.Main.main(Main.java:22)

And it was in the eclipse debug environment. Any help?


After that I tried to export it as runnable jar, and it works. But I cannot switch the code for debug and export each time. It should be in this way!

È stato utile?

Soluzione 2

The getClass().getResourceAsStream will find a resource base on the classpath.

So you must sure that the file you want to open is in the class path. As I see you are trying to find the file in the src/kan/master_ship.txt which is not in the class path. try /kan/master_ship.txt and make sure you have the kan folder and a master_ship.txt file in it and the folder is in the class path.

In the eclipse the class path is usually named target.

Altri suggerimenti

You are not able to provide correct path. It could be well when you test it from source ide but it would be fail when you referenced it for runnable jar.

try to put it in constructor and reference it. it work for me once.

public myClass(){
BufferedInputStream file= (BufferedInputStream) this.getClass().getResourceAsStream("resources/a.txt");
        try {
            System.out.println((char)file.read());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top