5.文件拷贝

来源:互联网 发布:logo设计自动生成软件 编辑:程序博客网 时间:2024/06/06 10:39
import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;import java.util.concurrent.ExecutionException;
public class TestDemo {private static final int BLOCK_SIZE = 20*1024*1024; public static void singleThreadRWFile1(File file, File newFile) throws IOException {FileInputStream is = new FileInputStream(file);FileOutputStream os = new FileOutputStream(newFile);byte[] buffer = new byte[4096];while (is.read(buffer) != -1){ os.write(buffer);}is.close();os.close();}public static void singleThreadRWFile2(File file, File newFile) throws IOException{FileChannelin = new FileInputStream(file).getChannel(),out = new FileOutputStream(newFile).getChannel();ByteBuffer bytebuffer = ByteBuffer.allocate(4096);while (in.read(bytebuffer) != -1){bytebuffer.flip();out.write(bytebuffer);bytebuffer.clear();}in.close();out.close();}public static void singleThreadRWFile3(File file, File newFile) throws IOException{FileChannelin = new FileInputStream(file).getChannel(),out = new FileOutputStream(newFile).getChannel();in.transferTo(0, in.size(), out);//out.transferFrom(in, 0, in.size());in.close();out.close();}public static void clear(File newFile) throws IOException{if (newFile.exists()){newFile.delete();newFile.createNewFile();}}public static void main(String[] args) throws IOException, InterruptedException, ExecutionException {// TODO Auto-generated method stubFile file = new File("E:/copy1.mp4");File newFile = new File("E:/copy2.mp4");if (!newFile.exists()){newFile.createNewFile();}long begin, end;begin = System.currentTimeMillis();singleThreadRWFile1(file, newFile);end = System.currentTimeMillis();System.out.println("singleThreadRWFile1() spend time:" + (end-begin) + "s");clear(newFile);begin = System.currentTimeMillis();singleThreadRWFile2(file, newFile);end = System.currentTimeMillis();System.out.println("singleThreadRWFile2() spend time:" + (end-begin) + "s");clear(newFile);begin = System.currentTimeMillis();singleThreadRWFile3(file, newFile);end = System.currentTimeMillis();System.out.println("singleThreadRWFile3() spend time:" + (end-begin) + "s");System.out.println("main over");}}

1 0