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!
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 ap.flush()as well?) at the end of your process to close the file output stream