*介绍 ---GatheringByteChannel和ScatteringByteChannel接口,实现对有序字节数组的读取,使得协议数据和固定数组内容的处理更加方便. ---实现类 Datagr...
*介绍
---GatheringByteChannel和ScatteringByteChannel接口,实现对有序字节数组的读取,使得协议数据和固定数组内容的处理更加方便.
---实现类
DatagramChannel,SocketChannel,FileChannel,SinkChannel
---GatheringByteChannel,long write(ByteBuffer[] srcs, int offset, int length)
srcs,数据来源; offset,srcs数组的偏移量; length,获取最大srcs的个数.
long,返回写入的个数.
---ScatteringByteChannel,long read(ByteBuffer[] dsts, int offset, int length)
dsts,要写入的数组; offset,开始使用的buffer位置; length,使用的最大buffer数
*示例,
ChannelGatherTest示例/**
* Feb 23, 2011 by dzh
*/
package channel;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @author dzh
* 协议,name[名字]|sex[性别],分隔符"|"
* 获取数据,去除分割符,写入person.txt文件
*/
public class ChannelGatherTest {
private static final String SEPERATOR ="\\|";
private static final String ENCODING ="utf-8";
private static final String DATA ="戴忠|男"; //源数据
private static final String TPATH ="/home/dzh/gather.txt"; //文件路径
public static void main(String[] args) throws Exception {
ByteBuffer[] bufs =scatterData();
gatherData(bufs);
}
private static void gatherData(ByteBuffer[] bufs) throws Exception{
File file =new File(TPATH);
if(!file.exists())
file.createNewFile();
FileOutputStream fos =new FileOutputStream(file);
FileChannel fc =fos.getChannel();
while(fc.write(bufs)>0){
//do others
};
fos.close();
}
private static ByteBuffer[] scatterData() throws Exception{
String[] data =DATA.split(SEPERATOR);
ByteBuffer nameBuf =ByteBuffer.wrap(data[0].getBytes(ENCODING));
ByteBuffer sexBuf =ByteBuffer.wrap(data[1].getBytes(ENCODING));
return new ByteBuffer[]{nameBuf,sexBuf};
}
}