**
1.定义:
“通道”:用于文件的读、写等操作
**
实例:
复制文件:
FileInputStream in =new FileInputStream(file1);
FileOutputStream out =new FileOutputStream(file2);
FileChannel os =in.getChannel();
FileChannel oss=out.getChannel();
ByteBuffer byteBuffer =ByteBuffer.allocate(100); //限制buffer空间大小 可以写(int)file.length
if((os.read(byteBuffer)!=-1)) //即int read (获取文件长度)= os.read(byteBuffer) 将文件file1经过文件流读入到buffer中 调用的是信道的read方法,底层会调用缓冲区的put方法
{
byteBuffer.flip(); // flip buffer file->buffer to buffer to file 写入与获取反转
oss.write(byteBuffer); // 向文件file2写入bybufferneirong
byteBuffer.clear(); //清空
}
oss.close();
os.close(); //使用完FileChannel后,必须将它关闭,调用close方法
out.close();
in.close();`
bytebuffer.rewind()
//rewind() 使缓冲区为重新读取已包含的数据做好准备:它使限制保持不变,将位置设置为 0。(也就是相当于选取当前缓冲去总的全部有效数据)和clear()类似,只是不改动限制.
bytebuffer.clear()
//clear() 使缓冲区为一系列新的通道读取或相对放置 操作做好准备:它将限制设置为容量大小,将位置设置为 0。 通道读取指从通道将数据读入到buffer中,相对放置是从位置开始将数据插入到buffer中clear()用来初始化缓存空间,例如读取文件时将文件内容置入缓存时要先执行此方法。