NIO网络编程(三)—— 分散读和集中写
这一篇博客中想记录下一种思想和方法——分散读和集中写。
分散读
分散读是当要读取一部分数据,并且这部分数据最后要送入不同的Buffer中,一种方法是先把他全部都进来,然后分给不同的Buffer,另一种就是使用一个channel,将数据直接送入不同的Buffer中,需要注意的是,这些Buffer的大小应该设置成他应该存入数据的大小。channel中有read()函数,参数可以是一个buffer,也可以是一个buffer数组,可以将需要读入的buffer组成一个buffer数组进行分散读。
比如说一个文件中存储了一个字符串"onetwothree",要把他们送入三个Buffer中,即第一个buffer存储"one",第二个存储"two",第三个存储"three",可以使用分散读的方式:
public class TestScatteringRead {
public static void main(String[] args) {
try (FileChannel channel = new RandomAccessFile("data.txt","r").getChannel()) {
ByteBuffer b1 = ByteBuffer.allocate(3);
ByteBuffer b2 = ByteBuffer.allocate(3);
ByteBuffer b3 = ByteBuffer.allocate(5);
channel.read(new ByteBuffer[]{b1,b2,b3});
ByteBufferUtil.debugAll(b1);//可视化buffer内容
ByteBufferUtil.debugAll(b2);//可视化buffer内容
ByteBufferUtil.debugAll(b3);//可视化buffer内容
} catch (IOException e) {
}
}
}
结果:
集中写
集中写的思想是当有多个buffer想要写到一个文件中时,同样有两种方式,第一个是遍历每一个buffer,然后把各自的内容输出到文件中,第二个是集中写的方法,即使用一个channel,直接把所有buffer的内容放入文件中。channel中有函数write(),同样的,可以给这个函数传入一个buffer数组,进行集中写。
public class TestGatheringWrite {
public static void main(String[] args) {
ByteBuffer b1 = StandardCharsets.UTF_8.encode("hello");
ByteBuffer b2 = StandardCharsets.UTF_8.encode("world");
ByteBuffer b3 = StandardCharsets.UTF_8.encode("你好");
try (FileChannel fileChannel = new RandomAccessFile("data2.txt", "rw").getChannel()) {
fileChannel.write(new ByteBuffer[]{b1,b2,b3});
} catch (IOException e) {
}
}
}
结果(写入到data2.txt内容):