欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【Java NIO 简例】FileChannel 数据传输

程序员文章站 2022-03-07 19:20:19
...

原文:《Java NIO Channel to Channel Transfers

 

FileChannel 的 transferFrom 和 transferTo 方法可以方便地将数据传入 FileChannel(写文件)或 读取 FileChannel 中的数据(读文件)

这两个方法比简单的 循环 读取-写入 更高效。因为许多操作系统能直接将 源Channel 中的数据传输到 文件系统缓存中,而无需真正地复制这些数据

transferFrom

该方法可以读取一个 ReadableByteChannel 中的数据,并传入 FileChannel。

FileChannel fromChannel = new RandomAccessFile("from.txt", "r").getChannel();
FileChannel toChannel = new RandomAccessFile("to.txt", "rw").getChannel();
long position = 0;
long count = fromChannel.size();
toChannel.transferFrom(fromChannel, position, count);

如果 fromChannel 当前可提供的数据量小于指定的数据量(count),则只传输这些可提供的数据。
如 fromChannel 是 SocketChannel,只有当前就绪的数据会被传输到 toChannel,即使后续有更多数据进入 fromChannel。

 

transferTo

该方法可以读取 FileChannel 中的数据,并传入一个 WritableByteChannel

FileChannel fromChannel = new RandomAccessFile("from.txt", "r").getChannel();
FileChannel toChannel = new RandomAccessFile("to.txt", "rw").getChannel();
long position = 0;
long count = fromChannel.size();
fromChannel.transferTo(position, count, toChannel);

该方法与 transferFrom 相似,调换了 fromChannel 与 toChannel

与 transferFrom 一样,如果 fromChannel 当前可提供的数据量小于指定的数据量(count),则只传输这些可提供的数据。

相关标签: nio