Java 实现复制图片

420 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

通过Java的OutputStream和InputStream实现图片的复制功能。

步骤如下:

  • 定义FileInputStream对象来读取图片
  • 定义FileOutputStream对象来写入图片
  • 调用FileInputStream对象的read函数来读字节
  • 调用FileOutputStream对象的write函数写字节
  • 关闭输入流和输出流

完整代码如下:

/**
 * Author:wangbl
 * Date:2022/2/8
 * Time:13:45
 * Description:使用字节流实现复制图片功能
 **/
public class CopyPicture {
    public static void main(String[] args) {
        //图片资源
        FileInputStream fileInputStream = null;
        //需要粘贴的图片资源
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream("a.jpg");
            fileOutputStream = new FileOutputStream("b.jpg");
            //定义一个字节数组,用来充当缓存区
            byte[] bytes = new byte[1024];
            int length = 0;
            //通过while循环将读取的字节写入到字节数组中,如果== -1则表示已经读取完毕
            while ((length = fileInputStream.read(bytes)) != -1){
                //将字节数组写入文件
                fileOutputStream.write(bytes,0,length);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭输入流和输出流
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

纸上得来终觉浅,绝知此事要躬行。开发这条路只有自己动手才能有所突破,看一百遍不如动手敲一遍。加油,小伙伴~