在Java NIO中,你可以直接将数据从一个Channel
传输(transfer)到另一个Channel
,前提是其中一个Channel
是FileChannel
。FileChannel
类的transferTo()
和transferFrom()
方法就是干这个的。
transferFrom()
FileChannel.transferFrom()
方法可以将源Channel
的数据传输到FileChannel
上。下面是个简单例子:
RandomAccessFile fromFile = new RandomAccessFile("data/fromFile.txt", "rw");
FileChannel fromChannel = fromFile.getChannel();
RandomAccessFile toFile = new RandomAccessFile("data/toFile.txt", "rw");
FileChannel toChannel = toFile.getChannel();
long position = 0;
long count = fromChannel.size();
toChannel.transferFrom(fromChannel, position, count);
参数position
和count
代表目标文件从哪(position
)开始写,最大(count
)传输多少字节。如果源Channel
的数据量没有count
大,则只会传输源Channel
数据量大小的数据。
此外,一些SocketChannel
的实现只会传输该SocketChannel
此时此刻已经读到内部Buffer
的数据,尽管这个SocketChannel
后续可能会读入更多数据。因此,它可能不会将请求(request)的全部(count
)数据从SocketChannel
传输至FileChannel
。
transferTo()
FileChannel.transferTo()
方法可以将一个FileChannel
的数据传输给另一个其他的Channel
。下面是个简单例子:
RandomAccessFile fromFile = new RandomAccessFile("data/fromFile.txt", "rw");
FileChannel fromChannel = fromFile.getChannel();
RandomAccessFile toFile = new RandomAccessFile("data/toFile.txt", "rw");
FileChannel toChannel = toFile.getChannel();
long position = 0;
long count = fromChannel.size();
fromChannel.transferTo(position, count, toChannel); // 只有这行不一样
注意,这个例子和前面的例子非常相似。唯一的不同就是调用方法的FileChannel
对象不一样,其他都没变化。
SocketChannel
的缺陷在transferTo()
方法依然存在。SocketChannel
的实现只会从FileChannel
传输数据直至填满Buffer
,然后就停止了。
说明
发现貌似有人在看这个系列文章了,有必要说明下,这个Java NIO系列来源于jenkov.com,本文只是翻译,希望大家千万不要误会,本文不是原创。原文地址:Java NIO。
网友评论