nio ScatterAndGather的API(二)

来源:互联网 发布:https默认端口号 编辑:程序博客网 时间:2024/05/05 01:10
package Demo2;import java.io.FileNotFoundException;import java.io.IOException;import java.io.RandomAccessFile;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;public class ScatterAndGather {private static String filePath = "D:\\2.txt";public static void main(String[] args) {Scatter();Gather();}//一个通道写入到多个缓冲区public static void Scatter(){try {RandomAccessFile afile = new RandomAccessFile(filePath, "rw");FileChannel channel = afile.getChannel();ByteBuffer headBuf = ByteBuffer.allocate(10);ByteBuffer bodyBuf = ByteBuffer.allocate(20);ByteBuffer[] bArray = new ByteBuffer[]{headBuf,bodyBuf};try {long n = channel.read(bArray);System.out.println("从通道里读出到多个字节:"+n);//为什么不是从第一个开始读20个字节?//注意buffer首先被插入到数组,然后再将数组作为channel.read() 的输入参数。//read()方法按照buffer在数组中的顺序将从channel中读取的数据写入到buffer,//当一个buffer被写满后,channel紧接着向另一个buffer中写。//Scattering Reads在移动下一个buffer前,必须填满当前的buffer,这也意味着它//不适用于动态消息(译者注:消息大小不固定)。换句话说,如果存在消息头和消息体,消息头必须//完成填充(例如 128byte),Scattering Reads才能正常工作。bodyBuf.flip();while(bodyBuf.hasRemaining()){System.out.print((char)bodyBuf.get()+"-------");}headBuf.flip();while(headBuf.hasRemaining()){System.out.print((char)headBuf.get()+"======");}System.out.println();/*while(n != 0){headBuf.flip();while(headBuf.hasRemaining()){System.out.print((char)headBuf.get()+"======");}System.out.println();bodyBuf.flip();while(bodyBuf.hasRemaining()){System.out.print((char)bodyBuf.get()+"-------");}}为什么不需要外层的条件呢?*/headBuf.clear();bodyBuf.clear();afile.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}//多个buffer写入同一个通道//buffers数组是write()方法的入参,write()方法会按照buffer在数组中的顺序,//将数据写入到channel,注意只有position和limit之间的数据才会被写入。因此,如//果一个buffer的容量为128byte,但是仅仅包含58byte的数据,那么这58byte的数据//将被写入到channel中。因此与Scattering Reads相反,Gathering Writes能较好的处理动态消息。public static void Gather(){try {RandomAccessFile aFile = new RandomAccessFile(filePath, "rw");FileChannel channel = aFile.getChannel();ByteBuffer header = ByteBuffer.allocate(128);ByteBuffer body = ByteBuffer.allocate(1024);ByteBuffer[] bArray = new ByteBuffer[]{header,body};try {//从多个缓冲区写进通道long n = channel.write(bArray);System.out.println("多个缓冲区写入通道的size:"+n);header.flip();body.flip();while(header.hasRemaining()){System.out.print((char)header.get()+"==");}while (body.hasRemaining()) {System.out.print((char)body.get()+"--");}header.clear();body.clear();aFile.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}