import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class Copy {
public static void main(String[] args) throws IOException {
//该文件3.82G
String readPath = "D://Win10-x64.GHO";
String writePath = "E://Win10-x64.GHO";
// copyFileByNIO(readPath, writePath);
// copyFileByFileInputString(readPath, writePath);
// copyFileByBuffer(readPath, writePath);
copyFile(readPath, writePath);
}
private static void copyFileByNIO(String readPath, String writePath) throws IOException {
long start = System.currentTimeMillis();
FileInputStream fis = new FileInputStream(readPath);
FileOutputStream fos = new FileOutputStream(writePath);
FileChannel readChanel = fis.getChannel();
FileChannel writeChanel = fos.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(8192);
while (true) {
buffer.clear();
int length = readChanel.read(buffer);
if (length == -1) {
break;
}
buffer.flip();
writeChanel.write(buffer);
}
readChanel.close();
writeChanel.close();
System.out.println( "NIO :" + (System.currentTimeMillis() - start));
}
private static void copyFileByFileInputString(String readPath, String writePath) throws IOException {
long start = System.currentTimeMillis();
byte[] b = new byte[8192];
FileInputStream dis = new FileInputStream(readPath);
FileOutputStream dos = new FileOutputStream(writePath);
while((dis.read(b))!=-1){
dos.write(b);
}
dis.close();
dos.close();
System.out.println( "FileInputString :" + (System.currentTimeMillis() - start));
}
private static void copyFileByBuffer(String readPath, String writePath) throws IOException {
long start = System.currentTimeMillis();
BufferedInputStream dis = new BufferedInputStream(new FileInputStream(readPath) );
BufferedOutputStream dos = new BufferedOutputStream(new FileOutputStream(writePath) );
byte[] b = new byte[8192];
while((dis.read(b))!=-1){
dos.write(b);
}
dis.close();
dos.close();
System.out.println("Buffer :" +( System.currentTimeMillis() - start));
}
public static void copyFile(String readPath, String writePath) throws IOException {
long start = System.currentTimeMillis();
File source = new File(readPath);
File target = new File(writePath);
FileInputStream is = new FileInputStream(source);
FileChannel in = is.getChannel();
FileOutputStream os = new FileOutputStream(target);
FileChannel out = os.getChannel();
long position = 0;
long size = in.size();
while (position <= size) {
long transfer = in.transferTo(position, size, out);
if (transfer <= 0) {
break;
}
position += transfer;
}
System.out.println(System.currentTimeMillis() - start);
}
}
分别使用inputStream ,buffer,FileChannel 进行read,write 。读写3.82G的文件,耗时基本一致,5秒左右。
使用FileChannel 的transferTo 方法,耗时 2秒左右。
我用的测试电脑是使用的ssd,速度较快,如果使用机械硬盘速度会慢很多。
FileChannel 的transferTo 方法是其他方法效率两倍多。