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中

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容