Problems with BufferedReader / PrintWriter?

Go To StackoverFlow.com

5

I'm using BufferedReader and PrintWriter to go through each line of an input file, make a change to some lines, and output the result. If a line doesn't undergo a change, it's just printed as is to the output file. For some reason however, the process ends prematurely. The code looks something like this:

BufferedReader in = new BufferedReader(new FileReader("in.txt"));
FileOutputStream out = new FileOutputStream("out.txt");
PrintWriter p = new PrintWriter(out);
String line = in.readLine();

while(line!=null)
{
   if(line is special)
      do edits and p.println(edited_line);
   else
      p.println(line);

   line = in.readLine();
}

However, for some odd reason, this process ends prematurely (actually prints out a half of a line) towards the very end of my input file. Any obvious reason for this? The while loop is clearly being ended by a null. And it's towards the end of my 250k+ line txt file. Thanks!

2009-06-16 15:00
by Monster
Are you absolutely sure that no exceptions are being thrown? What would you do if an exception was thrown? Would it be logged - Jon Skeet 2009-06-16 15:03
Jon - don't forget that PrintWriter squeltches exceptions - you have to use the "checkError" method to see if one occurred - MetroidFan2002 2009-06-16 15:04
Yes, but BufferedReader and FileReader don't - so the call to readLine() could have thrown - Jon Skeet 2009-06-16 15:12
What I'm saying is - since checkError isn't invoked, if PrintWriter threw an exception, it wouldn't be realized by this code. This is a common problem when using PrintWriter.. - MetroidFan2002 2009-06-16 16:06


7

Where do you flush/close your PrintWriter or FileOutputStream ? If the program exits and this is not done, not all your results will be written out.

You need out.close() (possibly a p.flush() as well?) at the end of your process to close the file output stream

2009-06-16 15:03
by Brian Agnew
Closing is better than simply flushing. + - Michael Myers 2009-06-16 15:04
Don't forget to do this in a finally block in case there's an exception - Jon Skeet 2009-06-16 15:12
That should be p.close(). p.flush() should not be necessary but it's good to know that the PrintWriter does not flush before it closes the underlying stream. If that stream has a bug (-> doesn't flush on close, either), you'll have the same problem again - Aaron Digulla 2009-06-16 15:32


1

Try adding a p.flush() after the loop.

2009-06-16 15:03
by skaffman


1

PrintWriter does not have autoflushing enabled, so its likely that the last bit of the file is not flushed before the program terminates.

Adding a p.flush() after your while loop should do the trick.

2009-06-16 15:03
by z -
Ads