0

I' getting NullPointerException when I'm trying to read a file and fill an array with the file's data. I'm calling the method straight from the constructor, after creating a new object in a main function. i tried, moving the br.close() line after reading some comments of similar problem people had, but had no success in that.

public void readFile (String fileName){
    // try read from the file
    try {
        FileReader fr = new FileReader(fileName);
        BufferedReader br = new BufferedReader(fr);
        String str;
        str = br.readLine();
        String[] s = str.split(" ");
        int col = Integer.parseInt(s[1]);
        int row = Integer.parseInt(s[2]);
        this.a = new int[col][row];
        for(int i = 0; i < a.length; i++) {
            str = br.readLine();
            String[] s1 = str.split(" "); 
            if (str != null){
                for(int j = 0; j < a[0].length; j++){
                    a[j][i] = Integer.parseInt(s1[j]);                      
                }
            }

        }
        if(br != null){
            br.close();
            fr.close();
        }
    }
    catch(IOException ex) {
        System.out.print("Error reading file\n" + ex);
        System.exit(2);
    }
}
rkosegi
  • 14,165
  • 5
  • 50
  • 83
  • What's the point of `if (str != null)` *after* doing `str.split(" ")`? What is the point of `if(br != null)`, since it can never be null? – Andreas Jan 14 '17 at 08:48
  • the file has jumps in some lines, making empty lines i don't want to work with, so before going forwards i make sure it's not empty – Mark Entelis Jan 14 '17 at 08:49
  • `str != null` is not a test for empty, it's a test for end-of-file. For empty test, use `! str.isEmpty()`. – Andreas Jan 14 '17 at 08:50

0 Answers0