分散读取与聚集写入
Posted toov5
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了分散读取与聚集写入相关的知识,希望对你有一定的参考价值。
分散读取与聚集写入
分散读取(scattering Reads):将通道中的数据分散到多个缓冲区中
聚集写入(gathering Writes):将多个缓冲区的数据聚集到通道中
package com.toov5.Nio; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class BufferTest03 { public static void main(String[] args) throws IOException { //随机访问 RandomAccessFile raf = new RandomAccessFile("test.txt", "rw"); //拿到通道 FileChannel channel = raf.getChannel(); //分配制定大小缓冲区 ByteBuffer buffer1 = ByteBuffer.allocate(100); ByteBuffer buffer2 = ByteBuffer.allocate(1024); //分散读取 ByteBuffer[] buffers = {buffer1,buffer2}; //通道里面进行读取 channel.read(buffers); //写入完毕之后 for 循环 for(ByteBuffer byteBuffer : buffers) { //切换成读的模式 byteBuffer.flip(); } System.out.println(new String(buffers[0].array(),0,buffers[0].limit())); System.out.println("*****************************************"); System.out.println(new String(buffers[1].array(),1,buffers[1].limit())); System.out.println(".....聚集读取........."); RandomAccessFile randomAccessFile = new RandomAccessFile("test2.txt", "rw"); //获取通道 FileChannel channel2 = randomAccessFile.getChannel(); channel2.write(buffers); randomAccessFile.close(); raf.close(); } }
分散读取 聚集写入
以上是关于分散读取与聚集写入的主要内容,如果未能解决你的问题,请参考以下文章