Search code examples
javasplittext-filesthread-exceptions

World Loader wont load world1.txt as an String


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)

Solution

  • 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!