Java 实现复制图片

通过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();
            }
        }
    }
}

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

  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

無昂博奥

测试下大赏功能,请勿大赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值