分散读取(Scattering Reads)
- 是指从 Channel 中读取的数据“分散”到多个 Buffer 中
- 注意:按照缓冲区的顺序,从 Channel 中读取的数据依次将 Buffer 填满。
聚集写入(Gathering Writes)
- 是指将多个 Buffer 中的数据“聚集”到 Channel。
- 注意:按照缓冲区的顺序,写入 position 和 limit 之间的数据到 Channel
@Test
public void test1(){
RandomAccessFile raf1 = null;
RandomAccessFile raf2 = null;
try {
raf1 = new RandomAccessFile("1.txt","rw");
Channel channel1= raf1.getChannel();
ByteBuffer bf1 = ByteBuffer.allocate(100);
ByteBuffer bf2 = ByteBuffer.allocate(1024);
ByteBuffer[] bfs = {bf1,bf2};
((FileChannel) channel1).read(bfs);
for(ByteBuffer buffer : bfs){
buffer.flip();
}
System.out.println(new String(bfs[0].array(),0,bfs[0].limit()));
System.out.println(new String(bfs[1].array(),0,bfs[1].limit()));
raf2 = new RandomAccessFile("2.txt","rw");
FileChannel channel = raf2.getChannel();
channel.write(bfs);
channel.close();
channel1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e){
}
}
管道数据传输
方法 | 说明 |
---|
transferFrom() | 将数据从源通道传输到其他 Channel 中: |
transferTo() | 将数据从源通道传输到其他 Channel 中: |
public void test5() {
try {
FileChannel inChannel = FileChannel.open(Paths.get( "a.png"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("3.png"), StandardOpenOption.WRITE, StandardOpenOption.READ,StandardOpenOption.CREATE);
outChannel.transferFrom(outChannel,0,inChannel.size());
inChannel.close();
outChannel.close();
}catch (IOException e){
}
}
FileChannel 的常用方法
方法 | 说明 |
---|
int read(ByteBuffer dst) | 从 Channel 中读取数据到 ByteBuffer |
long read(ByteBuffer[] dsts) | 将 Channel 中的数据“分散”到 ByteBuffer[] |
int write(ByteBuffer src) | 将 ByteBuffer 中的数据写入到 Channel |
long write(ByteBuffer[] srcs) | 将 ByteBuffer[] 中的数据“聚集”到 Channel |
long position() | 返回此通道的文件位置 |
FileChannel position(long p) | 设置此通道的文件位置 |
long size() | 返回此通道的文件的当前大小 |
FileChannel truncate(long s) | 将此通道的文件截取为给定大小 |
void force(boolean metaData) | 强制将所有对此通道的文件更新写入到存储设备中 |
字符集 : 编码 与 解码 Charset类
public void test2() throws CharacterCodingException {
Charset gbk = Charset.forName("GBK");
CharsetEncoder ce = gbk.newEncoder();
CharsetDecoder cd = gbk.newDecoder();
CharBuffer charBuffer = CharBuffer.allocate(102);
charBuffer.put("你好");
charBuffer.flip();
ByteBuffer byteBuffer = ce.encode(charBuffer);
for(int i =0; i < byteBuffer.limit(); i ++){
System.out.print(byteBuffer.get());
}
byteBuffer.flip();
CharBuffer charBuffer1 = cd.decode(byteBuffer);
System.out.println(charBuffer1.toString());
System.out.println("-----------------");
Charset utf = Charset.forName("utf-8");
CharBuffer decode = utf.decode(byteBuffer);
}