public class NioTest4 {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream("test1.txt");
FileOutputStream fileOutputStream = new FileOutputStream("test2.txt");
FileChannel inputChannel = fileInputStream.getChannel();
FileChannel outputChannel = fileOutputStream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
//考虑 clear 方法的必要性
buffer.clear();
int read = inputChannel.read(buffer);
if (read == -1) {
break;
}
//每次读取 到 写操作 必须要有flip 方法
buffer.flip();
outputChannel.write(buffer);
}
inputChannel.close();
outputChannel.close();
}
}
文件复制流程
test1.txt--->FileInputStream -->FilInputChannel --->read操作 -->buffer-->write操作--->FilOutputChannel -->FileOutputStream
-->text2.txt
3个重要属性状态的含义
position limit capacity(详见buffer源码)
capacity 容量
limit 上限
position 位置 ,缓冲区下一个要被读或者写的元素的索引
flip方法 重置 双指针 limit 和position
limit = position;
position = 0;
clear 方法
position = 0;
limit = capacity;
可以理解为 利用 双指针 limit 和position 往内存数组中读写数据
0<=mark<=position<=limit<=capacity
channel 只可能是单向的
stream 有可能是双向的
详见:https://github.com/njniecong/JavaDemo/tree/master/java/nio