JAVA IO 从零实践 (8.NIO 管道之间通信 transferFrom和transferTo)

管道之前通信

在上一篇的末尾 我们完成了一个代码实践, 就是文件的复制。
它的数据流向:

数据从源文件(srcFile)通过文件输入流(fileInputStream)被读取。

通过fileInputStream.getChannel()获取到源文件通道(srsChannel)。

在循环中,数据从源文件通道(srsChannel)读取到缓冲区(buffer)中,通过srsChannel.read(buffer)实现。

缓冲区的数据被切换到读模式(buffer.flip())。

数据从缓冲区(buffer)通过目标文件通道(destChannel)写入到目标文件中,通过destChannel.write(buffer)实现。

循环继续,直到源文件通道(srsChannel)读取到的数据为-1,表示已经读取完整个源文件,此时跳出循环。

关闭源文件通道(srsChannel)和目标文件通道(destChannel)。

也就是说 buffer 作为一个中转站 连接了 两头的两个channel。

那么有没有更便捷的方法 不用这种中转站, 让数据之间从一个channel到另一个channel呢??

这就是管道之间的通信——transferFrom和transferTo

transferFrom和transferTo

理解了前面的内容 这里就非常简答了:
这里只用了一行代码:

destChannel.transferFrom(srsChannel,srsChannel.position(),srsChannel.size();

就搞了这一篇中的这一大块:

  //缓冲区是channel与实际数据的中转站
            ByteBuffer buffer =ByteBuffer.allocate(1024);

            while (true){
                buffer.clear();
                int flag = srsChannel.read(buffer);
                if(flag==-1){
                    break;
                }
                buffer.flip();
                destChannel.write(buffer);
            }

是不是很神奇

public class transferFromAndToWithChannel {
    public static void main(String[] args) {

        try {
            File srcFile = new File("D:\\JavaProject\\fileTestPath\\client\\data01.txt");
            File destFile = new File("D:\\JavaProject\\fileTestPath\\server\\data01.txt");

            FileInputStream fileInputStream = new FileInputStream(srcFile);
            FileOutputStream fileOutputStream = new FileOutputStream(destFile);

            FileChannel srsChannel = fileInputStream.getChannel();
            FileChannel destChannel = fileOutputStream.getChannel();

            //不需要buffer 之间在通道之前复制数据
            destChannel.transferFrom(srsChannel,srsChannel.position(),srsChannel.size());

            srsChannel.close();
            destChannel.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}


慢慢熟练掌握了NIO之后 你就可以优雅的说:
”BIO 我们以后 不要再联系了 我怕NIO误会“

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值