先贴一下demo代码,是测试代码,记录一下使用方式,put那行有bug
//fileChannel
//1,输入输出流。2,RadmomAccessFile
try (FileChannel channel = new FileInputStream("txt").getChannel()){
//准备缓冲区
ByteBuffer buffer = ByteBuffer.allocate(10);
//ByteBuffer buffer2 = ByteBuffer.allocate(3);
//ByteBuffer buffer3 = ByteBuffer.allocate(3);
//ByteBuffer[] bbs = new ByteBuffer[]{buffer,buffer2,buffer3};
while (true){
int i = channel.read(buffer); //从channel读取数据,向buffer写入
//long j = channel.read(bbs);
if (i == -1){
break;
}
//打印buffer的内容
buffer.flip();//切换buffer的读取模式
while(buffer.hasRemaining()){
byte b = buffer.get();
//buffer.position();//读取或者写入的启始位置
//buffer.limit();//读取或者写入的限制位置
buffer.put("aaa".getBytes());
System.out.println(b);
//buffer.put("aaa".getBytes());
}
buffer.clear();//切换至写模式
}
} catch (IOException e) {
e.printStackTrace();
}
bytebuffer的结构
有三个重要属性:
capacity是指容量
position读写指针,代表当前读写的位置
limit读写的限制,代表代表最多可读、可写多少字节
初始化(ByteBuffer buffer = ByteBuffer.allocate(10))之后
各个属性大概为下图样子
在向bytebuffer写入数据之后
新的bytebuffer默认为写入状态
写入abcd之后,position就会移动到d的位置等待下一次写入,Limit写入限制和容量相等
此时切换为读模式
使用flip()方法切换至读模式
position会移动到读模式的开始位置,limit就是最多读取长度的位置,也就是d的位置
读取时,每调用一次get()方法,position位置就会前进一位,直到与limit相同
使用clear()方法切换至写模式
清除bytebuffer中写入的数据并切换至写模式,此时恢复至初始化状态