views:

652

answers:

4

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!

+1  A: 

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

skaffman
+1  A: 

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.

yx
+7  A: 

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

Brian Agnew
Closing is better than simply flushing. +1
Michael Myers
Don't forget to do this in a finally block in case there's an exception.
Jon Skeet
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
A: 

Ah, duh! Thanks all of you!

Monster