Search code examples
javaiobufferedreader

NumberFormatException when I try to read text file of integers into a int[]


I am very confused. I am trying to get 10 integers on 10 lines of a text file into an int[]. I have tried a few different ways, but my latest attempt is to use a for loop and parseInt on the BufferedReader.readLine() for each line of the file. This is returning a NumberFormatException every time.


public class InversionCounter {

    static int[] fileToArray(String filename) {
        File file = new File(filename);
        try ( BufferedReader br = new BufferedReader(new FileReader(file))) {
        int numOfLine = Integer.parseInt(br.readLine());
        int[] ourArray = new int[10];

        for (int i = 0; i < ourArray.length; i++)  {
            ourArray[i] = numOfLine;
            numOfLine = Integer.parseInt(br.readLine());
        }


        return ourArray;

        }  catch (NumberFormatException e) {
        System.out.println("NumberFormatException");
        } catch (FileNotFoundException e) {
            System.out.println("File not found");
        } catch (IOException e) {
            System.out.println("IO Exception");
        }

        return null;
    }

    public static void main(String[] args) throws IOException {
        fileToArray("/home/paris/coolfile");

    }



        }

Error:

Exception in thread "main" java.lang.NumberFormatException: null
    at java.base/java.lang.Integer.parseInt(Integer.java:614)
    at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at InversionCounter.fileToArray(InversionCounter.java:16)
    at InversionCounter.main(InversionCounter.java:30)

The file is simply this:

45
67
87
76
7
4
5
23
5675
3

Solution

  • The problem occurs when the line of the file has been read here:

    int numOfLine = Integer.parseInt(br.readLine());
    

    Quoting the javadoc of BufferedReader.readLine()

    Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached without reading any characters.

    You need to test if the line read is null before parsing it, otherwise Integer.parseInt() will throw a NumberFormatException.

    This is a simple fix:

    String line = br.readLine();
    if (line == null) {
        break;
    }
    int numOfLine = Integer.parseInt(line);
    

    A better approach is to not assume a certain quantity of input and just keep reading lines until the end of file (ie until line is null), adding them to a List<Integer>.