java 下载网络图片并保存到本地

java 下载网络图片并保存到本地

第一种

/**
     * 下载网络图片
     * @param urlList  网络路径
     * @param path  保存路径
     */
    public static void downloadPicture(String urlList,String path) {
        URL url = null;
        try {
            url = new URL(urlList);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());

            FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        String baiduLogoUrl = "https://www.baidu.com/img/bd_logo1.png";
        File localFile = new File("E:\\test\\" + "bd_logo1.png");
        downloadPicture(baiduLogoUrl,"E:\\test\\bd_logo1.png");
    }

第二种

/**
 * 保存网络图片到本地
 * @param imageUrl 网络地址
 * @param savePath 要保存到的本地地址
 */
public static void downloadImage(String imageUrl, String savePath) {
    try {
        //建立图片连接
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        //设置请求方式
        connection.setRequestMethod("GET");
        //设置超时时间
        connection.setConnectTimeout(10*1000);

        //输入流
        InputStream stream = connection.getInputStream();
        int len = 0;
        byte[] test = new byte[1024];
        //输出流,图片输出的目的文件
        BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(savePath));

        //以流的方式上传
        while ((len =stream.read(test)) !=-1){
            fos.write(test,0,len);
        }
        //记得关闭流,不然消耗资源
        stream.close();
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值