Java NIO 通道之间的数据传输
在Java NIO中,如果两个通道中有一个是FileChannel,那你可以直接将数据从一个channel 传输到另外一个channel。
transferFrom()
FileChannel的transferFrom()方法可以将数据从源通道传输到FileChannel中
下面的代码实现文件的复制
package com.viashare.channel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
/**
* Created by Jeffy on 16/5/17.
*/
public class ChannelMain {
private static final String PATH_FROM = "/Users/jeffy-pc/Downloads/test.txt";
private static final String PATH_TO = "/Users/jeffy-pc/Downloads/test3.txt";
public static void main(String[] args) throws IOException {
copy();
}
private static final void copy() throws IOException {
FileInputStream randomAccessFileFrom = new FileInputStream(new File(PATH_FROM));
FileOutputStream randomAccessFileTo = new FileOutputStream(new File(PATH_TO));
FileChannel fromchannel = randomAccessFileFrom.getChannel();
FileChannel tochannel = randomAccessFileTo.getChannel();
long position = 0;
long count = fromchannel.size();
tochannel.transferFrom(fromchannel,position, count);
}
}
方法的输入参数position表示从position处开始向目标文件写入数据,count表示最多传输的字节数。如果源通道的剩余空间小于 count 个字节,则所传输的字节数要小于请求的字节数。
此外要注意,在SoketChannel的实现中,SocketChannel只会传输此刻准备好的数据(可能不足count字节)。因此,SocketChannel可能不会将请求的所有数据(count个字节)全部传输到FileChannel中。
transferTo()
是不是发现这个例子和前面那个例子特别相似?除了调用方法的FileChannel对象不一样外,其他的都一样。
上面所说的关于SocketChannel的问题在transferTo()方法中同样存在。SocketChannel会一直传输数据直到目标buffer被填满。
private static final void transferToCopy() throws IOException {
FileInputStream randomAccessFileFrom = new FileInputStream(new File(PATH_FROM));
FileOutputStream randomAccessFileTo = new FileOutputStream(new File(PATH_TO));
FileChannel fromchannel = randomAccessFileFrom.getChannel();
FileChannel tochannel = randomAccessFileTo.getChannel();
long position = 0;
long count = fromchannel.size();
fromchannel.transferTo(position, count,tochannel);
}