NIO边看边记 之 通道之间的数据传输(五)

来源:互联网 发布:sql删除表数据语句 编辑:程序博客网 时间:2024/06/06 12:46

两个通道之间可以相互传输数据,但是至少一个通道得是文件channel

1.transferFrom()

从一个channel中传输到另一个channel,目的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();//从position开始最多传输count个字节toChannel.transferFrom(position, count, fromChannel);

如果源通道中待传输的数据少于count个,则有多少数据传输多少数据,但是最多传输传输count个。当源通道是SocketChannel时只会将准备好的数据传输到FileChannel中。

2.transferTo()

从一个channel中传输到另一个channel,源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();//从position开始最多传输count个字节fromChannel.transfer (position, count, toChannel);

SocketChannel会一直传输数据直到目标buffer被填满。

0 0
原创粉丝点击