分散(Scatter)和聚集(Gather)
- 分散读取(Scattering Reads)是指从Channel中读取的数据“分散”到多个Buffer中。
注:按照缓冲区的顺序,从Channel中读取的数据依次将Buffer填满。 - 聚集写入(Gathering Writes)是指将多个Buffer中的数据聚集到Channel。
注:按照缓冲区的顺序,写入position和limit之间的的数据到Channel。
demo
@Test
public void test4() throws Exception {
RandomAccessFile raf1 = new RandomAccessFile("1.txt", "rw");
FileChannel channel1 = raf1.getChannel();
ByteBuffer buf1 = ByteBuffer.allocate(100);
ByteBuffer buf2 = ByteBuffer.allocate(1024);
ByteBuffer [] bufs = {buf1,buf2};
channel1.read(bufs);
for (ByteBuffer byteBuffer : bufs) {
byteBuffer.flip();
}
System.out.println(new String(bufs[0].array(),0,bufs[0].limit()));
System.out.println("-----------------");
System.out.println(new String(bufs[1].array(),0,bufs[1].limit()));
RandomAccessFile raf2 = new RandomAccessFile("2.txt", "rw");
FileChannel channel2 = raf1.getChannel();
channel2.write(bufs);
channel2.close();
channel1.close();
}
@Test
public void test6() throws Exception {
Charset charset = Charset.forName("GBK");
CharsetEncoder ce = charset.newEncoder();
CharsetDecoder cd = charset.newDecoder();
CharBuffer cb = CharBuffer.allocate(1024);
cb.put("中国共和");
cb.flip();
ByteBuffer bBuf = ce.encode(cb);
for (int i = 0; i < 8; i++) {
System.out.println(bBuf.get());
}
bBuf.flip();
CharBuffer cBuf = cd.decode(bBuf);
System.out.println(cBuf.toString());
System.out.println("-----------------");
bBuf.flip();
Charset charset2 = Charset.forName("UTF-8");
CharBuffer cBuf2 = charset2.decode(bBuf);
System.out.println(cBuf2.toString());
}
@Test
public void test5() {
Map<String, Charset> map = Charset.availableCharsets();
Set<Entry<String,Charset>> set = map.entrySet();
for (Entry<String, Charset> entry : set) {
System.out.println(entry.getKey() + "-->" + entry.getValue());
}
}