Java NIO 通道(二)通道之间的传输

FileChannel提供了一个功能可以直接将数据从一个channel传输到另一个channel。

transferFrom()

此方法提供了可以将数据从源通道传输到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);

1. 方法从position位置开始向目标文件写入数据,count表示最多传输的字节数。

2.如果源通道是SocketChannel时,它只会传准备好的数据(可能不足count字节)。

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

基本类似。主要掌握有这么个东西存在便于我们后续使用。

猜你喜欢

转载自blog.csdn.net/qq_32924343/article/details/80610386