1. 程式人生 > 其它 >【Java】四種方法複製視訊檔案比較

【Java】四種方法複製視訊檔案比較

package Demo4;

import java.io.*;

public class CopyMp4Demo {
    public static void main(String[] args) throws IOException {
//        記錄開始時間
        long startTime = System.currentTimeMillis();

//複製視訊
//        method1();
//        共耗時:57486毫秒
//        method2();
//        共耗時:98毫秒
//        method3();
//        共耗時:286毫秒
        method4();
//        共耗時:28毫秒
//        記錄結束時間

        long endTime = System.currentTimeMillis();
        System.out.println("共耗時:" + (endTime - startTime) + "毫秒");
    }

    //    方法1:基本位元組流一次讀寫一個位元組
    private static void method1() throws IOException {
        FileInputStream fis = new FileInputStream("C:\\Users\\muzih\\Desktop\\VID.mp4");
        FileOutputStream fos = new FileOutputStream("D:\\MyProject\\Java\\LearnJava1\\src\\Demo4\\mymp4.mp4");
        int by;
        while ((by = fis.read()) != -1) {
            fos.write(by);
        }
        fos.close();
        fis.close();
    }

    //方法2:基本位元組流一次讀寫一個位元組陣列
    private static void method2() throws IOException {
        FileInputStream fis = new FileInputStream("C:\\Users\\muzih\\Desktop\\VID.mp4");
        FileOutputStream fos = new FileOutputStream("D:\\MyProject\\Java\\LearnJava1\\src\\Demo4\\mymp4.mp4");
        byte[] bys = new byte[1024];
        int len;
        while ((len = fis.read(bys)) != -1) {
            fos.write(bys, 0, len);
        }

        fos.close();
        fis.close();
    }

    // 方法3   位元組緩衝流一次讀寫一個位元組
    private static void method3() throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\Users\\muzih\\Desktop\\VID.mp4"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\MyProject\\Java\\LearnJava1\\src\\Demo4\\mymp4.mp4"));
        int by;
        while ((by = bis.read()) != -1) {
            bos.write(by);
        }
        bos.close();
        bis.close();
    }
    // 方法4   位元組緩衝流一次讀寫一個位元組陣列
    private static void method4() throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\Users\\muzih\\Desktop\\VID.mp4"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\MyProject\\Java\\LearnJava1\\src\\Demo4\\mymp4.mp4"));
        byte []bys=new byte[1024];
        int len;
        while ((len = bis.read(bys)) != -1) {
            bos.write(bys,0,len);
        }
        bos.close();
        bis.close();
    }
}