Time execution speed
With small files, buffering usually makes little or no difference. However, it can be hard to predict if a file will always remain small.
You can run the following demo class on your host, to look for differences between
buffered and unbuffered input. With large files (~1 Meg), you might see a difference
of 2-3 times.
(In Java Platform Performance by Wilson and Kesselman, an example using a 370K JPEG file has a gain in
execution speed of 83x!)
import java.io.*; public final class BufferDemo { public static void main (String... arguments) { 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 file is a file which already exists and can be read. */ static public void readWithBuffer(File file) { try (Reader input = new BufferedReader(new FileReader(file))){ int data = 0; while ((data = input.read()) != -1){ //do nothing } } catch (IOException ex) { ex.printStackTrace(); } } /** * @param file is an existing file which can be read. */ static public void readWithoutBuffer(File file) { try (Reader input = new FileReader(file)){ int data = 0; while ((data = input.read()) != -1){ //do nothing } } catch (IOException ex){ ex.printStackTrace(); } } private static void verifyFile(File file) { if (file == null) { throw new IllegalArgumentException("File should not be null."); } if (!file.exists()) { throw new IllegalArgumentException ("File does not exist: " + file); } if (!file.isFile()) { throw new IllegalArgumentException("Should not be a directory: " + file); } if (!file.canWrite()) { throw new IllegalArgumentException("File cannot be written: " + file); } } }