先打個小廣告,關注辛星教程,我的微信號xinxing0913,該項目源碼所在的github地址: https://github.com/xinxing0913/xinxing-nio-guide。
在nio中,有兩個比較重要的概念,分別是Scatter與Gather,Scatter是分散,它可以把Channel中的數據寫入到多個Buffer中,而Gather則是聚合,它表示把多個Buffer中的數據寫入到同一個Channel中。
在我們經過前面多個范例的實戰之后,它并沒有什么難度,來看一個具體的代碼范例把:
/**
* 我們這里主要介紹Scatter和Gather
* Scatter即分散,它是把Channel中的數據寫入到多個Buffer中
* Gather即聚合,它是把多個Buffer中的數據寫入到同一個Channel
*/
public class Demo7 {
public static void main(String[] args) throws Exception {
Demo7 demo = new Demo7();
System.out.println("----scatter范例-----");
demo.scatter();
System.out.println("----gather范例-----");
demo.gather();
}
public void scatter() throws Exception {
ByteBuffer buffer1 = ByteBuffer.wrap("hello".getBytes());
ByteBuffer buffer2 = ByteBuffer.wrap("夢之都".getBytes());
ByteBuffer[] buffers = {buffer1, buffer2};
FileChannel channel = new RandomAccessFile("src/main/resources/demo07.txt", "rw").getChannel();
channel.write(buffers);
channel.close();
System.out.println("寫入文件操作成功");
}
public void gather() throws Exception{
ByteBuffer buffer1 = ByteBuffer.allocate(5);
ByteBuffer buffer2 = ByteBuffer.allocate(20);
ByteBuffer[] buffers = {buffer1, buffer2};
FileChannel channel = new RandomAccessFile("src/main/resources/demo07.txt", "rw").getChannel();
channel.read(buffers);
channel.close();
System.out.println("buffer1的內容是:" + new String(buffer1.array()));
System.out.println("buffer2的內容是:" + new String(buffer2.array()));
}
}
在上面的代碼中,并沒有什么難以理解的地方,我們來看一下具體的執行效果吧:
image.png
對于Scatter與Gather,我們就介紹到這里啦。