您的位置:首页 > 编程语言 > Java开发

Java NIO 通道和通道之间转换

2014-12-30 15:26 447 查看
在Java NIO中你可以将数据从一个通道直接转移到另一个通道,如果其中一个通道是FileChannel。在FileChannel类中有transferTo()和transferFrom()方法来实现这种转移。

transferFrom()

FileChannel.transferFrom()方法可以将数据从一个通道转移到一个特定的FileChannnel。下面是一个简单的示例:

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用来指定向目标文件写入多少字节的数据。如果源通道中不足count个字节,则有多少转移多少。
另外,一些SocketChannel也可以实现数据转移,只要它内置的缓冲区已经有数据,不管它后续还是否有数据达到。因此,可能不能讲将请求的全部数据从SocketChannel转移到FileChannel。

transferTo()

transferTo()方法将一个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();

fromChannel.transferTo(position, count, toChannel);
这个例子和上一个例子类似。唯一的不同时调用不同的FileChannel对象,其它都一样。
上面我们的提到的关于SocketChannel的问题在使用transferTo()方法时任然存在。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java nio