Java NIO series of tutorials (5) Data transmission between channels

Original link: http://ifeve.com/java-nio-channel-to-channel/

Author : Jakob Jenkov    Translator : Guo Lei      Proofreading: Zhou Tai

In Java NIO, if one of the two channels is a FileChannel, you can directly transfer data from one channel to another channel.

transferFrom()

FileChannel's transferFrom() method can transfer data from the source channel to the FileChannel ). Here is a simple example:

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

The input parameter position of the method indicates that data is written to the target file from position, and count indicates the maximum number of bytes transferred. If the remaining space on the source channel is less than count bytes, the number of bytes transferred is less than the requested number of bytes.
Also note that in the implementation of SoketChannel, SocketChannel will only transmit data that is ready at the moment (maybe less than count bytes). Therefore, the SocketChannel may not transfer all the requested data (count bytes) into the FileChannel.

transferTo()

The transferTo() method transfers data from FileChannel to other channels. Here is a simple example:

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

Did you find this example particularly similar to the previous one? Everything is the same except the FileChannel object on which the method is called.
The problems mentioned above about SocketChannel also exist in the transferTo() method. SocketChannel will continue to transmit data until the destination buffer is full.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326925587&siteId=291194637