World Loader wont load world1.txt as an String

45 Views Asked by At

I have a problem with my Java Game. When i want to export it, it wont load the World. I'll get an "Thread - 0" Exception. This is my function:

    private void loadWorld(String path){
    String file = World.class.getResourceAsStream(path).toString();
    file.toString();
    String[] tokens = file.split("\\s+");
    width = Utils.parseInt(tokens[0]);
    height = Utils.parseInt(tokens[1]);
    spawnX = Utils.parseInt(tokens[2]);
    spawnY = Utils.parseInt(tokens[3]);

    tiles = new int[width][height];
    for(int y = 0;y < height;y++){
        for(int x = 0;x < width;x++){
            tiles[x][y] = Utils.parseInt(tokens[(x + y * width) + 4]);
        }
    }
}

It needs to be loaded as a String since i need to split every String from it into an Array. What is the proper way to manage this?

EDIT: This is the Stack Trace:

C:\Users\User>java -jar C:\Users\User\Desktop\Game.jar
Exception in thread "Thread-0" java.lang.NullPointerException
    at dev.codenmore.tilegame.worlds.World.loadWorld(World.java:76)
    at dev.codenmore.tilegame.worlds.World.<init>(World.java:36)
    at dev.codenmore.tilegame.states.GameState.<init>(GameState.java:14)
    at dev.codenmore.tilegame.Game.init(Game.java:61)
    at dev.codenmore.tilegame.Game.run(Game.java:94)
    at java.lang.Thread.run(Unknown Source)
2

There are 2 best solutions below

2
Gandalf1783 On BEST ANSWER

I did it! I used the following code to read the file: InputStream stream = World.class.getResourceAsStream("/worlds/world1.txt"); Maybe it was Buggy but at least it works!

0
Max Alexander Hanna On

always start with the debugger my friend. i would pop up the debugger to see what path is being placed here World.class.getResourceAsStream(path)

a null pointer exception will tell you that youre passing into your function a null value which it cannot handle. further down the call stack, you have

at dev.codenmore.tilegame.worlds.World.loadWorld(World.java:76)

which basically tells you where your nullpointerexception has occured. your error stack trace was a dead giveaway to what the problem was here.

Good luck in your project