两个通道之间可以相互传输数据,但是至少一个通道得是文件channel。
1.transferFrom()
从一个channel中传输到另一个channel,目的channel作为调用方。
实例代码如下:
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();
//从position开始最多传输count个字节
toChannel.transferFrom(position, count, fromChannel);
如果源通道中待传输的数据少于count个,则有多少数据传输多少数据,但是最多传输传输count个。当源通道是SocketChannel时只会将准备好的数据传输到FileChannel中。
2.transferTo()
从一个channel中传输到另一个channel,源channel作为调用方。
实例代码如下:
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();
//从position开始最多传输count个字节
fromChannel.transfer (position, count, toChannel);
SocketChannel会一直传输数据直到目标buffer被填满。