6. Java NIO Channel到 Channel的数据传输

在Java NIO中,如果两个channel中有一个是FileChannel,你可以直接让数据从一个channel传输到另一个channel。FileChanneltransferTo()transferFrom()方法可以用来完成此操作。

transferFrom()

方法FileChannel.transferFrom()是将数据从一个源channel传输至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);

参数position和count,含义分别为,在目标文件中从哪里开始写,和一共要写多少数据。如果源channel含有少于count的byte那么就会少传输数据。

此外,一些SocketChannel的实现可能只允许传输其准备好的内部buffer的数据,即使后面SocketChannel还会有更多数据。所以它不会将所有的数据都传入到file channel中。

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

注意这个例子和之前的非常相似。除了调用方法的对象不一样以外都是一样的。

与SocketChannel相关的内容,和前面例子中提到的是一样的。


想要查看此教程的目录请点击:Java NIO教程目录贴地址

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容