IO字符流拷贝视频或图片等字节数据

IO字符流拷贝视频或图片等字节数据

复制视频的四种方式

小结:

  • 四种方法中最不建议第一种
  • 最推荐使用第四种(多使用缓冲字节流一次读写一个字节数组)
import java.io.*;

public class Copy {
    public static void main(String[] args) throws IOException{
        // 记录开始时间
        long start = System.currentTimeMillis();

        // 第一个方法
        // 3541ms
//        method1();

        // 第二个方法
        // 7ms
//        method2();

        // 第三个方法
        // 40ms
//        method3();

        // 第四个方法
        // 4ms
        method4();

        // 记录结束时间
        long end = System.currentTimeMillis();

        System.out.println("共耗时"+(end - start)+"毫秒");
    }
}

定义四个方法,解耦

使用基本字节流一次读写一个字节

private static void method1() throws IOException {
    // 源文件
    FileInputStream fileInputStream = new FileInputStream("java基础\\mv.mp4");
    // 目标文件
    FileOutputStream fileOutputStream = new FileOutputStream("java基础\\src\\com\\io\\mv\\copy\\mv.mp4");

    // 进行一次读写一个字节的读写操作
    int read;
    while ((read = fileInputStream.read()) != -1){
        fileOutputStream.write(read);
    }

    //释放资源
    fileInputStream.close();
    fileOutputStream.close();
}

使用基本字节流一次读写一个字节数组

private static void method2() throws IOException {
    // 源文件
    FileInputStream fileInputStream = new FileInputStream("java基础\\mv.mp4");
    // 目标文件
    FileOutputStream fileOutputStream = new FileOutputStream("java基础\\src\\com\\io\\mv\\copy\\mv.mp4");

    // 进行一次读写一个字节的读写操作
    byte[] bytes = new byte[1024];
    int read;
    while ((read = fileInputStream.read(bytes)) != -1){
        fileOutputStream.write(bytes,0,read);
    }

    //释放资源
    fileInputStream.close();
    fileOutputStream.close();
}

使用缓冲字节流一次读写一个字节

private static void method3() throws IOException {
    // 源文件
    BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("java基础\\mv.mp4"));

    // 目标文件
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("java基础\\src\\com\\io\\mv\\copy\\mv.mp4"));

    // 进行一次读写一个字节的读写操作
    int read;
    while ((read = bufferedInputStream.read()) != -1){
        bufferedOutputStream.write(read);
    }

    //释放资源
    bufferedInputStream.close();
    bufferedOutputStream.close();
}

使用缓冲字节流一次读写一个字节数组

private static void method4() throws IOException {
    // 源文件
    BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("java基础\\mv.mp4"));
    // 目标文件
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("java基础\\src\\com\\io\\mv\\copy\\mv.mp4"));

    // 进行一次读写一个字节的读写操作
    byte[] bytes = new byte[1024];
    int read;
    while ((read = bufferedInputStream.read(bytes)) != -1) {
        bufferedOutputStream.write(bytes, 0, read);
    }

    //释放资源
    bufferedInputStream.close();
    bufferedOutputStream.close();
}
posted @ 2022-01-26 13:44  CoderCatIce  阅读(117)  评论(0编辑  收藏  举报