1. 在Java NIO中,如果两个通道中有一个是FileChannel,那你可以直接将数据从一个channel(译者注:channel中文常译作通道)传输到另外一个channel。

(1)transferFrom():

  FileChannel的 transferFrom()方法可以将数据源通道 传输到 FileChannel中(译者注:这个方法在JDK文档中的解释为将字节从给定的可读取字节通道传输到此通道的文件中)。下面是一个简单的例子:

 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 个字节,则所传输的字节数要小于请求的字节数
  此外要注意,在SoketChannel的实现中,SocketChannel只会传输此刻准备好的数据(可能不足count字节)。因此,SocketChannel可能不会将请求的所有数据(count个字节)全部传输到FileChannel中。

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

  是不是发现这个例子和前面那个例子特别相似?除了调用方法的FileChannel对象不一样外,其他的都一样。
  上面所说的关于SocketChannel的问题在transferTo()方法中同样存在。SocketChannel会一直传输数据直到目标buffer被填满。

最新文章

  1. vue.js 渲染完成回调
  2. CSS+DIV两栏式全屏布局
  3. typeof升级版,可以识别出array、object、null、nan、[]、{}
  4. 理解sparse coding
  5. 【BZOJ2793】【数学】[Poi2012]Vouchers
  6. hdu 5945 Fxx and game(单调队列优化DP)
  7. Microsoft Visual Studio 打开代码出现乱码解决方案
  8. 《Java技术》的第二次作业
  9. C#调用Bartender打印
  10. 【摘】Oracle执行计划不走索引的原因总结
  11. AHK控制鼠标与键盘
  12. mybatis插入数据并返回自增Id
  13. linux 下配置svn
  14. 给你的手机加上安全保障,请设置SIM卡PIN码
  15. 学c++需要先学c语言吗?
  16. linux中内存超出后可以这样
  17. 微信文档采用第三方方式打开选择qq
  18. fatal One or more refs for names blocks change upload
  19. 1024 Palindromic Number (25)(25 point(s))
  20. JNI 在命令行窗口输入字符,不显所输入字符,显指定的掩饰符

热门文章

  1. 新 esb-cs-tool.jar 参数说明
  2. LightOJ 1341 - Aladdin and the Flying Carpet (唯一分解定理 + 素数筛选)
  3. hdu 1199 Color the Ball
  4. Framewrok损坏导致卸载不了的解决办法
  5. Tomcat设置自己的项目为默认项目(用IP访问的是自己的项目)
  6. NSNotificationCenter需要注意的几个问题
  7. Flex圆角矩形
  8. Qtwebkit flashplayer插件问题
  9. vim复制多行<转>
  10. 学会自己写jQuery插件(一)---基础