I have a simple program where i read from a text file. Text file contains a number 99. I read this number using a method named readFile. After reading it, i then call writeFile method which increments the number read from the text file by 1 and the again saves it in the text file.
Method to read from file
public void readFile() {
String line = "";
try(FileReader fr = new FileReader("Room Number.txt");
BufferedReader br = new BufferedReader(fr)) {
while((line = br.readLine()) != null) {
roomNumberField.setText(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
writeFile(line);
}
Problem
As you can see in the above method, i am reading the data from file in a String variable line and at the end of the method, i call writeFile method and pass the line variable in to this method. In the writeFile method, before i can increment the line variable by 1, i have to parse it as int but doing so throws NumberFormatException. Now in my case, this exception will only be thrown only if line cannot be parsed as an int. At first i thought it could be because of line variable containing any space, so i called trim method on it which then threw NullPointerException which led me to believe that line is null.
Question is, why is line variable null ? it is initialized in while loop so how can it be null at the end of the method ?
PS. Number is read from the file correctly and if i move writeFile(line); inside while loop of readFile method, it doesn't throws any exception and my program works as it should.