用缓冲字节流,复制一个照片

时间:2022-07-28
本文章向大家介绍用缓冲字节流,复制一个照片,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.代码

package d01_TestInput;/*
 * zt
 * 2020/8/7
 * 12:02
 *边读边写
 */

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class CopyFiel {
    public static void main(String[] args) throws Exception {
        //1.创建缓冲流
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("e:\aaa\1.jpg"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("e:\aaa\2.jpg"));
        //2.边读编写
        byte[] buf = new byte[1024];
        int len = 0;
        while((len=bis.read(buf))!=-1){
            //bos.write(buf,0,len); 0 len 保证两个文件大小一样,要不然复制后的文件会超过源文件
            bos.write(buf,0,len);
            bos.flush();
        }
        //关闭
        bis.close();
        bos.close();
        System.out.println("赋值完毕");
    }
}

2.运行结果

赋值完毕

Process finished with exit code 0

要想两个图片的大小是一样的必须在 bos.write(buf,0,len);里面加0,len。 防止到最后一次循环的时候,复制整个数组

//bos.write(buf,0,len); 0 len 保证两个文件大小一样,要不然复制后的文件会超过源文件
            bos.write(buf,0,len);