/**
* 使用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();
}