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!
The Scanner has a little buffer (1KB char buffer) as opposed to the BufferedReader (8KB byte buffer), but it's more than enough. BufferedReader is a bit faster as compared to Scanner because the Scanner does the parsing of input data and BufferedReader simply reads a sequence of characters.
println is preferred when we have to print a lot of items as PrintWriter is faster than the other to print data to the console.
The constructor creates an object for the file and also creates a disk file: PrintWriter output = new PrintWriter( "myOutput. txt" ); If the file already exists its contents will be destroyed unless the user does not have permission to alter the file.
It's most commonly used for writing data to human readable text files or reports. In our first example, we'll use PrintWriter to create a new file by passing in the filename to its constructor as a string. If the file doesn't exists, it will be created.
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
Try adding a p.flush() after the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With