Question

I have to make a project for school; it's a game. I load the map from a text file. Currently I do it with a scanner, but I can't manage to get it working in a Runnable JAR file without putting the res file next to the JAR file. I want to get the text file inside; it worked with BufferedImages, but the text file doesn't work. I have this code:

public String ReadTextFile(String path) throws IOException {
    String HoldsText= null;

    FileReader fr = new FileReader(getClass().getResource(path).toString());
    BufferedReader br = new BufferedReader(fr);

    while((HoldsText = br.readLine())!= null){
        System.out.println(HoldsText);
    }

    return HoldsText;
}

path = "res/Maps/Map2.txt"

error:

java.lang.NullPointerException
at aMAZEing.TextManager.ReadTextFile(TextManager.java:22)
at aMAZEing.Map.openFile(Map.java:89)
at aMAZEing.Map.<init>(Map.java:31)
at aMAZEing.Board.<init>(Board.java:50)
at aMAZEing.Maze.<init>(Maze.java:24)
at aMAZEing.Maze.main(Maze.java:15)

file structure: http://speedcap.net/sharing/screen.php?id=files/a9/77/a977e8b487f21e67db941a96087561cd.png

This doesn't seem to work though. I've researched a lot but could not find anything that worked for me. I just need the whole text file in a string, the rest is easy with substring and so on.

EDIT!: The resolution to this was that my path had res in it, and it didn't work because of that. I deleted the res and got "/Maps/Map2.txt" as path, now the file loads and my map is displayed again.

Was it helpful?

Solution

public static String ReadTextFile(String path) throws IOException{
    String HoldsText= null;

    InputStream is = getClass().getResourceAsStream(path);
    InputStreamReader fr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(fr);

    StringBuilder sb = new StringBuilder();
    while((HoldsText = br.readLine())!= null){
        sb.append(HoldsText)
        .append("\n");
    }

    return sb.toString();
}

You need to append the lines and use InputStreamReader instead of FileReader

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top