IO将图片拷贝到本地

1.以IO流的方式拷贝

	/**
     * 下载图片到工程目录下或者本地
     *
     * @param dst      图片文件地址
     * @param fjname   图片name
     * @param fileData 图片输出流本项目orcler数据库是存的二进制数据流可以直接用
     */
    public void copyFile(String dst, String fjname, DeferredFileOutputStream fileData) {
        //1 提供读入 输出文件(字节流)(可以为txt 或者 图片 视频等)
        File file2 = new File(dst + "/" + fjname);
        //提供流对象
        FileOutputStream fos = null;
        try {
            if (!file2.exists()) {
                file2.createNewFile();
            }
            fos = new FileOutputStream(file2.getPath());
            fileData.writeTo(fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //先关输出
            try {
                if (fos != null) {
                    fos.close();
                }
                if (fileData != null) {
                    fileData.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

2.求方式(图片是网络上的图片)

	/**
     * 下载网络图片到本地
     *
     * @param src    网络图片地址 本服务器上的需要考虑登录问题 如果可以直接获取到项目库的输入流最好
     * @param dst
     * @param fjname
     */
    public void copyFile(String src, String dst, String fjname) {
        //1 提供读入 输出文件(字节流)(可以为txt 或者 图片 视频等)
        File file2 = new File(dst + "/" + fjname);
        //提供流对象
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            URL url = new URL(src);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();
            if (!file2.exists()) {
                file2.createNewFile();
            }
            fos = new FileOutputStream(file2.getPath());
            bos = new BufferedOutputStream(fos);
            //创建一个Buffer字符串
            byte[] buffer = new byte[1024 * 10];
            //每次读取的字符串长度,如果为-1,代表全部读取完毕
            int len = 0;
            //使用一个输入流从buffer里把数据读取出来
            while ((len = inStream.read(buffer, 0, 1024 * 10)) != -1) {
                //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
                bos.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //先关输出
            try {
                bos.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值