Java中的NIO详解Day05-Channel之间的数据传输
Channel之间的数据传输
- FileChannel
- transferFrom
- transferTo
FileChannel
- 在Java NIO中,如果两个通道中有一个是FileChannel. 那么可以直接将数据从一个channel传输到另一个channel
transferFrom
- FileChannel的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(position, count, fromChannel);
position: 从position处开始向目标文件写入数据
- count: 最多传输的字节数. 如果源通道的剩余空间小于count字节,则所传输的数据要小于请求的字节
- 在SocketChannel的实现中 ,SocketChannel只会传输此刻准备好的数据,可能不足count字节.所以 ,SocketChannel可能不会将请求的所有数据,即count个字节的数据.全部传输到FileChannel中
transferTo
- FileChannel的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);
position: 从position处开始向目标文件写入数据
- count: 最多传输的字节数. 如果源通道的剩余空间小于count字节,则所传输的数据要小于请求的字节
- 在SocketChannel的实现中 ,SocketChannel只会传输此刻准备好的数据,可能不足count字节.所以 ,SocketChannel可能不会将请求的所有数据,即count个字节的数据.全部传输到FileChannel中
还没有评论,来说两句吧...