JAVA NIO简明教程 六 通道之间数据传输

JAVA NIO简明教程 六 通道之间数据传输

在java nio你能在从一个通道直接传输数据到另一个通道,如果其中一个通道是FileChannel,这个类有transferTo()transferFrom()方法来进行数据传输。

transferFrom()

FileChannel.tranferFrom()方法能够从一个通道传输到文件类型的通道,下面是一个示例:

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

positioncount参数,设置游标的起点和大小。即使大小设置大了,也是可以传输的。

需要注意的,一些socketChannel的实现仅仅只能传输现在缓存中的数据,及时之后还能读到更多的数据。

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

需要注意的是上面的示例和第一个示例很相似。仅仅读写的方向不同,本质是一样的。
fileChaneel传输到socketchannel时使用tansferTo()方法时缓冲区已满的时候,将停止。

原文:http://tutorials.jenkov.com/java-nio/channel-to-channel-transfers.html

发布了121 篇原创文章 · 获赞 56 · 访问量 167万+

猜你喜欢

转载自blog.csdn.net/u013565163/article/details/84556480