Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with BufferedReader / PrintWriter?

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!

like image 758
Monster Avatar asked Jun 16 '09 15:06

Monster


People also ask

Why is Scanner slower than BufferedReader?

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.

Is PrintWriter fast?

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.

What happens if you construct a PrintWriter using the file name of an existing file?

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.

Does PrintWriter create a file if it doesn't exist?

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.


2 Answers

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

like image 59
Brian Agnew Avatar answered Sep 18 '22 16:09

Brian Agnew


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

like image 41
skaffman Avatar answered Sep 18 '22 16:09

skaffman