在Java NIO中,如果其中的一个通道是FileChannel,你可以直接从一个通道向另一个通道直接转换数据。FileChannel有一个transferTo和transferFrom方法来实现这个功能。
transferFrom()
FileChannel.transferFrom()方法将另一个通道的数据转换到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.transferFrom(fromChannel.position,count);
复制代码
参数position和count分别表明目标文件从哪里开始写,最大需要转换的字节数。如果源channel的长度小于count,则取小的那个。
另外,在SoketChannel的实现中,SocketChannel只会传输此刻准备好的数据(可能不足count字节)。因此,SocketChannel可能不会将请求的所有数据(count个字节)全部传输到FileChannel中。
transferTo()
transferTo方法负责将FileChannel转换到其他Channel.下面是一个简单的例子。
RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt","rw");
FileChannel fromChannel = fromFile.getChannle();
RandomAccessFile toFile = new RandomAccessFile("toFile.txt","rw");
FileChannel toChannel = toFile.getChannel();
long position = 0;
long count = fromChannel.size();
fromChannel.transferTo(position,count,toChannel);
复制代码
是不是发现这个例子和前面那个例子特别相似?除了调用方法的FileChannel对象不一样外,其他的都一样。 上面所说的关于SocketChannel的问题在transferTo()方法中同样存在。SocketChannel会一直传输数据直到目标buffer被填满。