0

I am receiving an error message for the parameter of my while loop. I do not understand why. I have initialized all the variables in the parameter. The program reads most of my input file but only prints about half of the output file, and it stops the output in the middle of a read line.

The error is:

Exception in thread "main" java.lang.NullPointerException
at dbreadfile.DBReadFile.main(DBReadFile.java:44)
Java Result: 1

The program is:

PrintWriter pw;
BufferedWriter bw;
FileWriter fw;
String line = "";
br = new BufferedReader(new FileReader(inFile));
fw = new FileWriter(outFile, true);
bw = new BufferedWriter(fw);
pw = new PrintWriter(bw);

while((line = br.readLine().trim()) != null){ //ERROR ON THIS LINE
   //do stuff
}//end while
user3342236
  • 69
  • 3
  • 8
  • 1
    If you reach the end of the file, `br.readLine()` is `null`. You can't call any methods, including `trim()`, on `null`... – bcsb1001 Sep 09 '15 at 18:46
  • But i wasn't reaching the end of the file. The output stopped in the middle of the data. Why would it do this? If I take the trim() out of the parameter it works just fine. So I added it inside the loop. – user3342236 Sep 09 '15 at 18:50
  • You said there was an NPE on that line. What could cause that? 1. `br` is `null` - no it isn't. 2. `br.readLine()` is `null`, which is returned [if the end of the stream has been reached](http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine()) (you have read the whole file). – bcsb1001 Sep 09 '15 at 18:52
  • ok. I understand that now. Thank you for your help. I will have to look further into why my output was all messed up but is now okay. Thank you again. – user3342236 Sep 09 '15 at 18:56

0 Answers0