測試檔案是一個壓縮包
測試時間硬體不同 結果不同 但是總的排名應該是: 直接緩沖區 > 非直接緩沖區 > 普通io
普通io測試 代碼如下:耗時5144ms
long start = System.currentTimeMillis();
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("F:\\00 GIT.zip");
fos = new FileOutputStream("F:\\10101GIT.zip");
byte bys[] = new byte[1024];
int len = 0;
//資料讀
while ((len = fis.read(bys)) != -1) {
//資料寫
fos.write(bys, 0, len);
}
fos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
long end = System.currentTimeMillis();
System.out.println("耗費時間為:" + (end - start));//耗費時間為:5144
非直接緩沖區測試:5091ms
long start = System.currentTimeMillis();
FileInputStream fis = null;
FileOutputStream fos = null;
//1.擷取通道
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
fis = new FileInputStream("F:\\00 GIT.zip");
fos = new FileOutputStream("F:\\999GIT.zip");
inChannel = fis.getChannel();
outChannel = fos.getChannel();
//2.配置設定指定大小的緩沖區
ByteBuffer buf = ByteBuffer.allocate(1024);
//3.将通道中的資料存入緩沖區中
while (inChannel.read(buf) != -1) {
buf.flip(); //切換讀取資料的模式
//4.将緩沖區中的資料寫入通道中
outChannel.write(buf);
buf.clear(); //清空緩沖區
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outChannel != null) {
try {
outChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inChannel != null) {
try {
inChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
long end = System.currentTimeMillis();
System.out.println("耗費時間為:" + (end - start));//耗費時間為:5091
long start = System.currentTimeMillis();
FileChannel inChannel = FileChannel.open(Paths.get("F:\\00 GIT.zip"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("F:\\11.zip"), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE);
//記憶體映射檔案
MappedByteBuffer inMappedBuf = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size());
MappedByteBuffer outMappedBuf = outChannel.map(MapMode.READ_WRITE, 0, inChannel.size());
//直接對緩沖區進行資料的讀寫操作
byte[] dst = new byte[inMappedBuf.limit()];
inMappedBuf.get(dst);
outMappedBuf.put(dst);
inChannel.close();
outChannel.close();
long end = System.currentTimeMillis();
System.out.println("耗費時間為:" + (end - start));//耗費時間為:1454