/**
* 使用NIO讀寫文件
* 1、根據輸入輸出流獲取相應的通道
* 2、創建緩衝區
* 3、從緩衝區讀出或者寫入字節流到相應的通道
* @throws Exception
*/
public void oprateFileByNio() throws Exception {
long beginTime = System.currentTimeMillis();
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(copyFile);
FileChannel inChannel = fis.getChannel(); //獲取輸入通道
FileChannel outChannel = fos.getChannel(); //獲取輸出通道
ByteBuffer mByteBuffer = ByteBuffer.allocate(1024); //分配緩衝區大小
while (true) {
mByteBuffer.clear(); //清除操作:將position設置爲0,limit(限制)設置爲capasity(容量)的大小
int r = inChannel.read(mByteBuffer); //將字節流從該通道讀入緩衝區
//r=-1時代表已經到達流的末尾
if (r == -1) {
break;
}
mByteBuffer.flip(); //反轉操作:將limit設置爲當前的position,再將position設置爲0
outChannel.write(mByteBuffer); //將緩衝區中字節流寫入該通道
}
inChannel.close();
outChannel.close();
fis.close();
fos.close();
}