JavaNIO - Scatter & Gather

Scatter & Gather指在多個緩衝區上實現一個簡單的 I/O 操作。減少或避免了Buffer間的拷貝和系統調用。

Channel Write操作

在這裏插入圖片描述
Write操作

Channel Read操作

在這裏插入圖片描述
Read操作
public class ChannelDemo {
    public static void main(String[] args) throws IOException {
        ByteBuffer buffer1 = ByteBuffer.allocate(4);
        ByteBuffer buffer2 = ByteBuffer.allocate(6);
        ByteBuffer[] buffers = {buffer1, buffer2};

        System.out.println("===Channel Read 即Scatter===");
        FileInputStream fis = new FileInputStream("d:/temp/x.dat");
        ScatteringByteChannel scatteringByteChannel = (ScatteringByteChannel) Channels.newChannel(fis);

        scatteringByteChannel.read(buffers);//數據從Channel 散佈到各個 buffers

        buffer1.flip();
        System.out.println(new String(buffer1.array()));
        System.out.println(new String(buffer2.array()));

        while (buffer1.hasRemaining()) {
            System.out.println(buffer1.get());
        }

        buffer2.flip();
        while (buffer2.hasRemaining()) {
            System.out.println(buffer2.get());
        }
        System.out.println("===Channel Write 即Gather===");
        buffer1.rewind();
        buffer2.rewind();

        FileOutputStream fos = new FileOutputStream("d:/temp/y.dat");
        GatheringByteChannel gatheringByteChannel = (GatheringByteChannel) Channels.newChannel(fos);
        buffers[0] = buffer2;
        buffers[1] = buffer1;
        gatheringByteChannel.write(buffers);//數據從各個 buffers 抽取到Channel
    }
}

在這裏插入圖片描述

Scatter& Gather優點

Scatter/Gather 操作會被翻譯爲適當的本地調用來直接填充或抽取緩衝區,減少或避免了緩衝區拷貝和系統調用

在這裏插入圖片描述
	public final Buffer clear() {
	     position = 0;
	     limit = capacity;
	     mark = -1;
	     return this;
	}
	public final Buffer rewind() {
	    position = 0;
	    mark = -1;
	    return this;
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章