Java中通過緩衝區提高I/O系能

    我們知道Java中一般的輸入輸出流類都是用單字節的讀取方法來進行I/O操作的,也就是說每次只讀寫一個字節的數據,這種方法顯然繁瑣低效。如果從設備讀取10M的文件,每次讀取一個字節,完成操作將需要做10M/次I/O操作,I/O操作又是一件相當耗時的事情,無疑在很大程度上降低了系統的性能。


    Java中專門提供提高I/O效率的緩衝類,這好比在數據讀寫時提供一個臨時緩衝區,每次讀取一個緩衝區大小的數據,將這數據庫一次性寫入目標設備。下圖中分別爲兩種讀取方式。

 


    舉個簡單例子,在A地有10000本書需要搬到B地,如果一次搬1本,需要10000次。如果每次取1000本放到一個貨車上,運到B地,需要10次完成。貨車相當於是緩存區。同樣道理,開設一個數據緩存區每次讀取一數據塊對於提高讀取效率有顯著提升。下面用一個具體代碼示例來表示二者的性能差別。

 

import java.io.*;

/*******************************************************************************
 * 
 * @author pengcqu
 * 
 */
public class TestBuffer {

	public static void main(String args[]) throws IOException {
		TestBuffer br = new TestBuffer();
		String from = "d:/a/1.MP3";
		long startTime = System.currentTimeMillis();
		br.readWrite(from,"d:/b/2.MP3");
		long endTime = System.currentTimeMillis();
		System.out.println("直接讀取耗時:" + (endTime - startTime) +"ms");
		long startTime1 = System.currentTimeMillis();
		br.readWriteWithBuffer(from, "d:/b/3.MP3");
		long endTime1 = System.currentTimeMillis();
		System.out.println("使用緩衝區讀取耗時:" + (endTime1 - startTime1) +"ms");
		

	}

	/***************************************************************************
	 * 直接讀取文件
	 * 
	 * @param from
	 * @param to
	 * @throws IOException
	 */
	public static void readWrite(String from, String to) throws IOException {
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new FileInputStream(from);
			out = new FileOutputStream(to);
			while (true) {
				int data = in.read();
				if (data == -1) {
					break;
				}
				out.write(data);
			}
		} finally {
			if (in != null) {
				in.close();
			}
			if (out != null) {
				out.close();
			}
		}
	}

	/***************************************************************************
	 * 使用緩存區讀寫文件
	 * @param from
	 * @param to
	 * @throws IOException
	 */
	public static void readWriteWithBuffer(String from, String to)
			throws IOException {
		InputStream inBuffer = null;
		OutputStream outBuffer = null;
		try {
			inBuffer = new BufferedInputStream(new FileInputStream(from));
			outBuffer = new BufferedOutputStream(new FileOutputStream(to));
			while (true) {
				int data = inBuffer.read();
				if (data == -1) {
					break;
				}
				outBuffer.write(data);
			}
		} finally {
			if (inBuffer != null) {
				inBuffer.close();
			}
			if (outBuffer != null) {
				outBuffer.close();
			}
		}
	}

}

  

結果:對於5.8M大小的文件,直接讀寫耗時:39266ms;使用緩衝區讀寫耗時:719ms。可見通過Buffer讀寫文件性能的明顯優於直接讀寫。

如有理解不妥之處,請各位高手補充意見。

 

 

 

相關鏈接:

★  Java知識點彙總 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章