[Java] Better I/O Performance : Buffered Stream

You can increase your I/O performance by the Buffered I/O technique when you are using the Java I/O methods,. The performance of Buffered I/O is better than Unbuffered I/O, since the Unbuffered I/O is byte-by-byte operation, and these operations are all going through the underlying OS. The procedure includes some expensive operations, so we should reduce the method-call to increase the program efficiency.


Fortunately, Java provides three I/O Strategies – Byte Stream, Buffered Stream, Custom Buffered Stream. In the Java Platform Performance: Strategies and Tactics – Chapter 4 – I/O Performance wrote by Steve Wilson and Jeff Kesselman. It explains how to implement the three strategies and also provides the estimation result. It shows the copy operation by Byte Stream Strategy spends 10800ms, and the cost of 2nd Custom Buffered Stream Strategy is only 22ms.

Here is a sample code for you,

 
/**
* Copy the source File into the target file
*
* @param sourceFile the file will be copied
* @param targetFileName the target filename
* @return true if the file is copied, false if failed to copy
* @throws IOException
*/
public boolean copyFile(InputStream sourceFile, String targetFileName) {
File file = new File(path, targetFileName);

try {
FileOutputStream fileOutputStream = new FileOutputStream(file);

int bytesRead;
while (true) {
synchronized (buffer) {
if ((bytesRead = sourceFile.read(buffer)) == -1)
break;
fileOutputStream.write(buffer, 0, bytesRead);
}
}

fileOutputStream.close();

} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "copyFileToAppData: Exception: " + e.toString());
e.printStackTrace();
return false;
}
return true;
}

Note:
1. Ensure the file stream has been closed when the stream is not used anymore. (The close method includes flush operation)
2. If you want to keep the  file stream lived, you need to call the flush method. Otherwise, the file content may be lose.
3. In the sample code, the some variables you should declare by yourself.

發佈留言