转载:自并发编程网ifeve.com编程
在Java NIO中,若是两个通道中有一个是FileChannel,那你能够直接将数据从一个channel(译者注:channel中文常译做通道)传输到另一个channel。并发
transferFrom():被动接收dom
FileChannel的transferFrom()方法能够将数据从源通道传输到FileChannel中(译者注:这个方法在JDK文档中的解释为将字节从给定的可读取字节通道传输到此通道的文件中)。socket
方法的输入参数position表示从position处开始向目标文件写入数据,count表示最多传输的字节数。若是源通道的剩余空间小于 count 个字节,则所传输的字节数要小于请求的字节数。
此外要注意,在SoketChannel的实现中,SocketChannel只会传输此刻准备好的数据(可能不足count字节)。所以,SocketChannel可能不会将请求的全部数据(count个字节)所有传输到FileChannel中。spa
transferTo():主动发送code
transferTo()方法将数据从FileChannel传输到其余的channel中。下面是一个简单的例子:对象
除了调用方法的FileChannel对象不同外,其余的都同样。
上面所说的关于SocketChannel的问题在transferTo()方法中一样存在。SocketChannel会一直传输数据直到目标buffer被填满。blog
例子:文档
@Test public void test2() { 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(); //从from 读到 本通道;注意socketfrom只会发送已经准备好的,不会发送count个 toChannel.transferFrom(fromChannel,position, count); //将本通道 写到 to;注意sockedfrom会一直发送,直到to被填满 fromChannel.transferTo(position, count, toChannel); }