Buffering usually appropriate

Buffering input/output is usually recommended, and should likely be the default style.

Unbuffered input/output classes operate only on one byte at a time. Using a buffer will often increase performance by large factors.

Example runs of the following BufferDemo, with text files of various sizes, shows gains of ~3x. (In Java Platform Performance by Wilson and Kesselman, an example using a 370K JPEG file has a gain in execution speed of 83x!)

Size -  624 bytes :
With buffering: 10 ms
Without buffering: 30 ms

Size - 10,610 bytes :
With buffering: 30 ms
Without buffering: 80 ms

Size - 742,702 bytes :
With buffering: 180 ms
Without buffering: 741 ms


import java.io.*;

public final class BufferDemo {

  public static void main (String... aArguments) {
    File file = new File("C:\\Temp\\blah.txt");
    verifyFile( file );

    Stopwatch stopwatch = new Stopwatch();

    stopwatch.start();
    readWithBuffer( file );
    stopwatch.stop();
    System.out.println("With buffering: " + stopwatch);

    stopwatch.start();
    readWithoutBuffer( file );
    stopwatch.stop();
    System.out.println("Without buffering: " + stopwatch);
  }

  /**
  * @param aFile is a file which already exists and can be read.
  */
  static public void readWithBuffer(File aFile) {
    try { 
      //use buffering, with default buffer size of 8K
      Reader input =  new BufferedReader( new FileReader(aFile) );
      try {
        int data = 0;
        while ((data = input.read()) != -1){
          //do nothing
        }
      } 
      finally {
         input.close();
      }
    }
    catch (IOException ex){
      ex.printStackTrace();
    }
  }

  /**
  * @param aFile is an existing file which can be read.
  */
  static public void readWithoutBuffer(File aFile) {
    try {
      Reader input =  new FileReader( aFile );
      try {
        //do not use buffering
        int data = 0;
        while ((data = input.read()) != -1){
          //do nothing
        }
      }
      finally {
        input.close();
      }
   }
   catch (IOException ex){
     ex.printStackTrace();
   }
 }

  private static void verifyFile( File aFile ) {
    if (aFile == null) {
      throw new IllegalArgumentException("File should not be null.");
    }
    if (!aFile.exists()) {
      throw new IllegalArgumentException ("File does not exist: " + aFile);
    }
    if (!aFile.isFile()) {
      throw new IllegalArgumentException("Should not be a directory: " + aFile);
    }
    if (!aFile.canWrite()) {
      throw new IllegalArgumentException("File cannot be written: " + aFile);
    }
  }
} 



See Also :
Time execution speed
Would you use this technique?
Yes   No   Undecided   
© 2013 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on August 30, 2012.
Over 2,400,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -