Java NIO(三)通道间的数据传输

在Java NIO中,如果两个通道中有一个是FileChannel,那你可以直接将数据从一个channel传输到另外一个channel。

RandomAccessFile fromFile =newRandomAccessFile("fromFile.txt","rw");

FileChannel      fromChannel = fromFile.getChannel();

RandomAccessFile toFile =newRandomAccessFile("toFile.txt","rw");

FileChannel      toChannel = toFile.getChannel();

longposition =0;

longcount = fromChannel.size();

toChannel.transferFrom(position, count, fromChannel);

方法的输入参数position表示从position处开始向目标文件写入数据,count表示最多传输的字节数。如果源通道的剩余空间小于 count 个字节,则所传输的字节数要小于请求的字节数。

RandomAccessFile fromFile =newRandomAccessFile("fromFile.txt","rw");

FileChannel      fromChannel = fromFile.getChannel();

RandomAccessFile toFile =newRandomAccessFile("toFile.txt","rw");

FileChannel      toChannel = toFile.getChannel();

long position =0;

long count = fromChannel.size();

fromChannel.transferTo(position, count, toChannel);

transferTo()方法将数据从FileChannel传输到其他的channel中

你可能感兴趣的:(Java NIO(三)通道间的数据传输)