在 Java NIO 中你可以从一个通道向另一个通道直接传输数据,如果一个 channel 是 FileChannel 类型的,那么他可以直接把数据传输到另一个 channel。逐个特性得益于FileChannel 类包含的 transferTo() 和 transferFrom() 两个方法。

阅读文章的过程中如果有任何疑问,欢迎添加笔者为好友,拉您进【七日书摘】微信交流群,一起交流技术,一起打造高质量的职场技术交流圈子,抱团取暖,共同进步。
七日书摘官方群.jpg

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);

transferFrom 的参数 position 和 count 表示目标文件的写入位置和最多写入的数据量。如果通道中的数据小于count 那么就传实际有的数据量。

另外,有些 SocketChannel 的实现在传输时只会传输哪些处于就绪状态的数据,即使 SocketChannel 后续会有更多可用数据。因此,这个传输过程可能不会传输整个的数据。

transferTo()

transferTo() 方法把 FileChannel 数据传输到其他的channel 中,下面是示例:

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);

这段代码和之前介绍 transfer 时的代码非常相似,区别只在于调用方法的是哪个 FileChannel ,本质上是一样的。

SocketChannel 的问题也存在与transferTo.SocketChannel 的实现可能只在发送的buffer 填充满后才发送,并结束。

英文原文链接:http://tutorials.jenkov.com/java-nio/channel-to-channel-transfers.html

------完------

推荐阅读:

Java NIO 简明教程 之 Java NIO 概述

Java NIO 简明教程 之 Java NIO Channel

Java NIO 简明教程 之 Java NIO 缓冲(Buffer)

Java NIO 简明教程 之 Java NIO Scatter/Gather

Java基础知识面试题篇(2020年2月最新版)

更技术学习请进入七日书摘官方群: 七日书摘官方群

七日书摘官方群群聊二维码.png

参考资源:
https://blog.csdn.net/u013565163/article/details/83539738
https://blog.csdn.net/Andrew_Yuan/article/details/80215164