NIO 通道之间数据传输
- transferFrom()
- transferTo()
假如两个Channel中有一个是FileChannel,NIO允许你将数据从其中一个Channel直接传输到另一个Channel。FileChannel有TransferTo() 、TransferFrom()的API可供使用。
TransferFrom()
FileChannel.transfrom():将数据从一个源Channel(比如SocketChannel)传输入一个FileChannel。下面是示例:
RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");
FileChannel fromChannel = fromFile.getChannel();
RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw");
FileChannel toChannel = toFile.getChannel();
long position = 0;
long count = fromChannel.size();
// 这里是toChannel
toChannel.transferFrom(fromChannel, position, count);
position、count参数说明了从position处开始向目标文件写入数据,count表示最多传输的字节数。如果源Channel的剩余字节数少于count,传输的字节数就少于请求字节数。
此外,一些SocketChannel实现可能只传输buffer中当前已准备好的数据()。因此,SocketChannel可能不会把请求数量(count)的所有数据从SocketChannel传输到FileChannel。
transferTo()
transferTo() 将FileChannel的数据传输到其他Channel中(比如SocketChannel)。下面是示例:
RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");
FileChannel fromChannel = fromFile.getChannel();
RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw");
FileChannel toChannel = toFile.getChannel();
long position = 0;
long count = fromChannel.size();
// 这里是fromChannel
fromChannel.transferTo(position, count, toChannel);
注意下这个例子和上面那个例子有何不同。真正不同的只是方法的调用方而已。其他都相同。
上面说的那个SocketChannel的问题对于同一个transferTo()方法也存在。SocketChannel实现可能会一直从FileChannel传输触发数据直到发送的buffer是空的,然后才停止。