博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java NIO 通道之间的数据传输(5)
阅读量:6966 次
发布时间:2019-06-27

本文共 1156 字,大约阅读时间需要 3 分钟。

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

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(position, count, fromChannel);//参数position表示从position处开始向目标文件写入数据,count表示最多传输的字节数。如果源通道的剩余空间小于count个字节,则所传输的字节数要小于请求的字节数

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

注:以上两个例子,在SoketChannel的实现中,SocketChannel只会传输此刻准备好的数据(可能不足count字节)。SocketChannel会一直传输数据直到目标buffer被填满。

转载于:https://www.cnblogs.com/chen970826/p/10985137.html

你可能感兴趣的文章
《C++ Primer Plus》16.1 string类 学习笔记
查看>>
NPOI之使用EXCEL模板创建报表
查看>>
晕,hibernate 的 merge和cascade="all-delete-orphan"要慎重合在一起使用
查看>>
成立23周年,大数据助力迪信通开启4.0时代征程
查看>>
酷!新款 iPad 可能将会取消 Home 键
查看>>
收快递成“新开门七件事” 京东小哥最暖心
查看>>
AMD又有大动作!2018CES期间牵手京东强势吸睛
查看>>
2017百度AI开发者大会 一场5000名开发者的分享盛宴
查看>>
野心外漏?Windows Defender或将独霸杀毒软件市场?
查看>>
重庆“90后”双胞胎“动妹” 守护春运回家路
查看>>
电影《蓝色生死恋》将上映 保留原版经典片段
查看>>
“中华龙乡”重庆铜梁举办首届中华龙灯艺术节
查看>>
探访广铁深圳“父女搭档”乘警出勤风采
查看>>
6月Python热文Top10,精选自1000篇文章
查看>>
Vue 折腾记 - (12) Nuxt.js写一个校验访问浏览器设备类型及环境的中间件
查看>>
使用 React 全家桶搭建一个后台管理系统
查看>>
腾讯云容器团队内部Istio专题分享
查看>>
当我说要做大数据工程师时他们都笑我,直到三个月后……
查看>>
【数据科学系统学习】Python # 数据分析基本操作[二] pandas
查看>>
第一批95后已经是阿里科学家了
查看>>