Java Buffered Writer Issue

  • Using Buffered Writers is an efficient way to write the output to a file where hard disk accesses are costly.
  • The main idea behind the Buffered Objects is(Here it is the buffered writer) having a buffer which is, writing the output to a memory location in the computer's main memory(which is faster than writing to hard disk). And then once the Buffer is filled with enough data, the whole buffer is written to the hard disk.
  • However, this can bring up some issues which are difficult to find. One of such issues is my attempt to write to a text file using a buffered writer. I used the following code.

FileWriter writer;
BufferedWriter bWriter;
PrintWriter pwriter;

writer = new FileWriter(new File("./output.txt");
bWriter = new BufferedWriter(writer);
pwriter=new PrintWriter(bWriter);


int i=0;

while(i<1000){
pwriter.println(i);
i++;
}

  • This should seem to print the numbers 0 to 999 each on a new line. But practically it printed only up to 658.
  • The cause for the issue was the use of Buffers for printing the output. The Buffered writer only writes to the disk once the buffer is full. The reason is that after printing line 658, the buffer does not become full till 999. So, there is still content left in the buffer which had not been written to disk.
  • To provide a better view of the example I would present a real world scenario which is similar.
  • Suppose a bus(analogous to the Buffered writer) has seating for 50 people. The bus moves from A to B only when the seats are full. So, if we were to transport 120 people from A to B, it would be as follows.
  • Trip 1: passengers 1 to 50 will be transported to B and Bus returns to A
  • Trip 2: passengers 51 to 100 are transported to B and Bus returns to A
  • Trip 3: passengers 101 to 120 get aboard the bus, but the bus does not transport them to B because the bus is not full. The third trip does not occur :-(
  • So, in such scenarios, we must force the bus to make a trip even though the bus is not full, because our number one objective is to transport all the 120 people from A to B. Efficiency and fuel cost would be number two on our list of importance.
In Java, you have a method to overcome the issue. Buffered Writers come with a method 'flush()'. When you invoke this method on the object, it does not care whether the buffer is full or not. It makes a disk write immediately.

Comments

Unknown said…
Thank You. Its is really worth reading this blog. This link will help beginners to get started: http://www.javatrainingchennai.in/

Popular posts from this blog

Encrypt and Decrypt Images Using Java

Build your own Network sniffer

ASP Response.Write newline