Problems with BufferedReader / PrintWriter?
-
05-07-2019 - |
Question
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!
Solution
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
OTHER TIPS
Try adding a p.flush() after the loop.
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.