Java NIO分散读 聚集写

#Java NIO分散读 聚集写


Java NIO 开始支持scatter/gather(分散读/聚集写),scatter/gather用于描述从channel中读取或者写入到channel的操作。

1. 概念

分散(scatter)从channel中读取是指在读操作的时候将读取的数据写入到多个buffer中,因此,channel将读取到的数据分散到多个buffer中。当一个buffer被写满之后,才会进行下一个buffer的写入。

聚集(scatter)是指将多个 Buffer 中的数据“聚集”到 Channel。一个buffer读完之后,才会进行下一个buffer的读入

2. 代码

public class ScatterReadAndGatheringWrite {
    public static void main(String[] args) {
        String src1 = "src/file.txt";
        String src2 = "src/file.copy.txt";
        ByteBuffer byteBuffer1 = ByteBuffer.allocate(1);
        ByteBuffer byteBuffer2 = ByteBuffer.allocate(100);
        byteBuffer1.clear();
        byteBuffer2.clear();
        ByteBuffer[] bufs={byteBuffer1, byteBuffer2};

        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(src1);
            FileChannel inChannel = fileInputStream.getChannel();

            fileOutputStream = new FileOutputStream(src2);
            FileChannel outChannel = fileOutputStream.getChannel();

            while (true) {

                //开始写数据到buffer中
                long r = inChannel.read(bufs);
                System.out.println(r);
                if (r == 0) {
                    break;
                }

                //切换到读模式
                for (ByteBuffer buffer : bufs) {
                    buffer.flip();
                }

                //System.out.println("buffer.position=" + byteBuffer1.position());
                //System.out.println("buffer.capacity=" + byteBuffer1.capacity());
                //System.out.println("buffer.limit=" + byteBuffer1.limit());
                outChannel.write(bufs);

            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

3. 参考文章

https://blog.csdn.net/qq_33804730/article/details/79171188
https://blog.csdn.net/jkxqj/article/details/77480006

你可能感兴趣的:(java,nio,分散读,聚集写)