NIO提供了Channel之间数据传输的方法。以FileChannel为例,该类提供了transferFrom和transferTo方法用于进行通道间传输。
transferFrom()
将另一个Channel的数据传入本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);
很简单的方法啦,从fromChannel中将指定位置后count数的数据传入本Channel。如果数据不足就少穿,如果是SocketChannel之类只传递内部缓存内现在已有数据的Channel,也可能不会把全部数据传过来。
transferTo()
范例
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.transferTo(position, count, toChannel);
也很简单,和上面的方法有相同的问题