您的位置:首页 > 编程语言 > Java开发

javaNIO之Scatter/Gather

2016-06-07 14:59 423 查看
这部分第一次看了一遍有点不知所云,现在再看一遍。

首先我们看看它的继承图:



这部分主要由两个类组成

1、继承了ReadableByteChannel类的ScatteringByteChannel,这个类只有read方法。它用于将一个流中的数据写到多个ByteBuffer中。

2、继承了WritableByteChannel类的GatheringByteChannel类,这个类只有writer方法。它用于将多个ByteBuffer中的数据写到一个流中。

Demo:(java NIO书上有个例子,但我只想说What Fuck?我只想默默地看看GatheringByteChannel的使用方式,能不能少一点套路!所以我写一个简单易懂的Demo)

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.GatheringByteChannel;

public class Demo5 {
public static void main(String[] args) throws IOException {
FileOutputStream outFile = null;
GatheringByteChannel outChannel = null;
try {
outFile = new FileOutputStream("D:\\test.txt");//要输出的目标文件
outChannel = outFile.getChannel();
ByteBuffer[] buffers= Demo5.getBuffers();//要输出的Buffer数组
outChannel.write(buffers);//直接把数组作为参数传输即可

} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{//关闭通道和输出流
if(outFile != null){
try {
outChannel.close();
outFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public static ByteBuffer[] getBuffers(){
ByteBuffer buffer1 = ByteBuffer.allocate(10);
ByteBuffer buffer2 = ByteBuffer.allocate(10);
ByteBuffer buffer3 = ByteBuffer.allocate(10);
buffer1.put("buffer1".getBytes());
buffer2.put("buffer2".getBytes());
buffer3.put("buffer3".getBytes());
//不要忘了翻转缓冲区
buffer1.flip();
buffer2.flip();
buffer3.flip();
ByteBuffer [] buffers= {buffer1, buffer2, buffer3};
//返回有3个ByteBuffer对象的数组
return buffers;
}
}


Gather的使用其实非常简单,书上写那么复杂我也是醉了。Scatter相同的思路使用即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java nio