BASIC
- NIO Channel中的scatter和gather机制
- scatter 从channel中读出写入到多个buffer中
- gather 从多个buffer中写入到一个一个channel
- transferFrom() & transferTo()
- 条件:一个channel是FileChannel
- 用于把数据从一个channel传到另一个channel
package nio_file;/**
* @author: create by liubh
* @date:2020/2/9
*/
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
/**
* @author: create by liubh
* @email lbhbinhao@gmail.com
* @date:2020/2/9
*/
/**
* NIO Channel中的scatter和gather机制
* scatter 从channel中读出写入到多个buffer中
* gather 从多个buffer中写入到一个一个channel
*/
public class ScatterAndGather {
public static void main(String[] args) throws IOException {
RandomAccessFile file = new RandomAccessFile("/test.txt","rw");
FileChannel channel = file.getChannel();
String msg = "Hello,dear Kingx.\r\n" +
"Don't\r\n leave me alone";
String[] s = msg.split("\r\n",2);
ByteBuffer head = ByteBuffer.allocate(s[0].length());
ByteBuffer body = ByteBuffer.allocate(s[1].length());
ByteBuffer[] buffers = {head,body};
channel.write(buffers);
/**
* transferFrom() & transferTo()
* 条件:一个channel是FileChannel
* 用于把数据从一个channel传到另一个channel
*/
RandomAccessFile file1 = new RandomAccessFile("/test1.txt","rw");
RandomAccessFile file2 = new RandomAccessFile("/test2.txt","rw");
FileChannel channel1 = file1.getChannel();
FileChannel channel2 = file2.getChannel();
long position = 0;
long count = channel2.size();
channel1.transferFrom(channel2,position,count);
}
}