nio

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Date;

public class Test {
    public static void main(String[] args){
        Test t = new Test();
        t.directBuffer();
        t.io();
    }

    public void directBuffer(){
        long time1 = new Date().getTime();
        File f = new File("F:/test");
        File film1 = new File("F:/test/01.mp4");
        File film2 = new File("F:/test/03.mp4");
        try {
            FileChannel fis = new FileInputStream(film1).getChannel();
            FileChannel fos = new FileOutputStream(film2).getChannel();

            ByteBuffer bb = ByteBuffer.allocateDirect(1024 * 1024);
            while(true){
                int read = fis.read(bb);
                if(read != -1){
                    bb.flip();
                    fos.write(bb);
                    bb.clear();
                }
                else{
                    break;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        long time2 = new Date().getTime();
        long time = time2 - time1;
        System.out.println("直接内存方法复制文件使用了" + time + "毫秒");
    }

    public void io(){
        long time1 = new Date().getTime();
        File f = new File("F:/test");
        File film1 = new File("F:/test/01.mp4");
        File film2 = new File("F:/test/02.mp4");
        try {
            FileInputStream fis = new FileInputStream(film1);
            FileOutputStream fos = new FileOutputStream(film2);

            byte[] b = new byte[1024 * 1024];
            while(true){
                int read = fis.read(b);
                if(read != -1){
                    fos.write(b);
                }
                else{
                    break;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        long time2 = new Date().getTime();
        long time = time2 - time1;
        System.out.println("普通nio方法复制文件使用了" + time + "毫秒");
    }
}

原文地址:https://www.cnblogs.com/clamp7724/p/11751527.html