Java NIO——分散读取与聚集写入

1.分散(Scatter)与聚集(Gather):

分散读取(Scattering Reads):将通道中的数据分散到多个缓冲区中

聚集写入(Gathering Writes):将多个缓冲区中的数据聚集到通道中

2.分散读取:

注意:按照缓冲区的顺序,从Channel中读取的数据依次将Buffer填满

public class TestChannel{
    @Test
    public void test4() throws IOException{
        RandomAccessFile raf1 = new RandomAccessFile("1.txt", "rw");

        //1.获取通道
        FileChannel channel1 = raf1.getChannel();

        //2.分配制定大小的缓冲区
        ByteBuffer buf1 = ByteBuffer.allocate(100);
        ByteBuffer buf2 = ByteBuffer.allocate(1024);

        //3.分散读取
        ByteBuffer[] bufs = {buf1 , buf2};
        channel1.read(bufs);

        for(ByteBuffer byteBuffer : bufs){
            byteBuffer.flip();
        }

        System.out.println(new String(bufs[0].array() , 0 , bufs[0].limit()));
        System.out.println("--------------");
        System.out.println(new String(bufs[1].array() , 0 , bufs[1].limit()));
    }
}

3.聚集写入:

public class TestChannel{
    @Test
    public void test4() throws IOException{
        RandomAccessFile raf2 = new RandomAccessFile("2.txt", "rw");

        //1.获取通道
        FileChannel channel2 = raf1.getChannel();

        //2.分配制定大小的缓冲区
        ByteBuffer buf1 = ByteBuffer.allocate(100);
        ByteBuffer buf2 = ByteBuffer.allocate(1024);

        //3.聚集写入
        ByteBuffer[] bufs = {buf1 , buf2};
        channel2.write(bufs);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38386085/article/details/82558570
今日推荐