對於百兆以內的中小文件,去使用緩衝字節流的提升I/O性能,對比文件字節流的執行效率提升不是很明顯,基本處於毫秒級差距。
但是對於G級文件,使用緩衝流的I/O操作效率顯著提升,以下記錄測試數據。
這裏用Movie.mkv做測試源,文件約2G大小。
先用文件字節輸入流測試讀入性能,以秒做單位統計最終執行時長。
代碼如下:
package com.Air;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class BufferDemo {
public static void main(String[] args) {
File file = new File("H:\\Movie.mkv");
FileInputStream in = null;
long startTime = System.currentTimeMillis();//獲取任務的起始時間
try {
in = new FileInputStream(file);
byte[] b_in = new byte[1024];//緩衝區
try {
while(in.read(b_in)!=-1) {
// TODO NOTHING
}
long endTime = System.currentTimeMillis();//獲取任務的終止時間
System.out.println("任務耗時:"+(endTime-startTime)/1000+"秒");
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if(in!=null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
測得用時:
然後測試緩衝流效率,代碼如下:
package com.Air;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class BufferDemo {
public static void main(String[] args) {
File file = new File("H:\\Movie.mkv");
FileInputStream in = null;
BufferedInputStream bfin = null;
long startTime = System.currentTimeMillis();//獲取讀取任務的起始時間
try {
in = new FileInputStream(file);
bfin = new BufferedInputStream(in);//包裝輸入字節流
byte[] b_in = new byte[1024];//緩衝區
try {
while(bfin.read(b_in)!=-1) {//使用緩衝輸入字節流bfin讀取
// TODO NOTHING
}
long endTime = System.currentTimeMillis();//獲取讀取任務的終止時間
System.out.println("任務耗時:"+(endTime-startTime)/1000+"秒");
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if(in!=null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bfin!=null) {
try {
bfin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
測試耗時如下:
利用緩衝流效率提升明顯。