Java input/output (IO) performance can be elevated using standard buffering classes, just as the operating system increases its speed by buffering requests. For example, if a piece of code requires reading data from a disk, it tries to read the data that is already in memory, and if the code wants to write something to the disk, it might store the output in memory for a while before it completes the write operation to wait for more data.
In a Java IO system, writing one character to memory is much faster than writing to disk, for example:
// 这段代码会抛出 IOException
Writer writer = new FileWriter( new File( "file.txt" ) );
for(int i=0; i〈1000; i++) {
writer.write(""+i);
writer.write(" ");
}
writer.close( );
In this example code, FileWriter output a number at a time, measuring the elapsed times on the Apple Powerbook, the first time in 180 milliseconds, and then 90 milliseconds, the difference may be caused by the JVM's Just-in-time (just-in-time) compilation.
Adding buffering to this code is to create a BufferedWriter object on the FileWriter.
//这段代码会抛出IOException
Writer writer = new BufferedWriter(new FileWriter(
new File( "file.txt" )
) );
for(int i=0; i〈1000; i++) {
writer.write(""+i);
writer.write(" ");
}
writer.close( );
Now BufferedWriter will decide at what frequency to send write calls to FileWriter. You can use the flush () method to force a write call. When BufferedWriter is added, the code runs for 63 milliseconds. If there are a lot of small output, then the performance improvement of BufferedWriter under the default condition is very significant.
In addition to BufferedWriter, Bufferedoutputstream also has the same quality, for the input is BufferedReader and bufferedinputstream.
Note that the buffer class is not only working on the file system, any reader/writer can be buffered to increase the speed of character input/output, and any outputstream/inputstream can be buffered to increase the speed of byte io.