java-图片下载

本文详细介绍了一种使用Java批量下载并保存网络图片的方法。通过示例代码展示了如何利用HttpURLConnection进行图片的GET请求,设置超时时间,以及如何处理响应,将图片流转换为字节数组并保存到本地指定路径。此方法适用于需要自动化下载大量图片的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

图片下载

    public static void main(String[] args) {
        List<String> urlList = new ArrayList<String>();
        urlList.add("http://www.neeq.com.cn/uploads/1/image/public/201606/20160615155145_kugr388dtr.png");

        uploadImg(urlList);
    }

    private static void uploadImg(List<String> urlList){
        String filepath = "C:\\Users\\huage\\Desktop\\n3b_nq\\secrities_img";
        if( urlList != null && urlList.size() > 0 ){
            for (int i = 0; i < urlList.size(); i++) {
                String url = urlList.get(i);
                try {
                    getImages(url, filepath+"\\"+i+url.substring(url.lastIndexOf(".")));
                } catch (Exception e) {
                    System.out.println(e.getMessage()+":------------>"+url);
                }
            }
        }
    }
        
    /**
     * 图片路径
     * @param urlPath
     * @param fileName:图片存放地址,和名称
     * @throws Exception
     */
    public static void getImages(String urlPath,String fileName) throws Exception{
        URL url = new URL(urlPath);//:获取的路径
        //:http协议连接对象
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setReadTimeout(6 * 10000);
        if (conn.getResponseCode() <10000){
            InputStream inputStream = conn.getInputStream();
            byte[] data = readStream(inputStream);
            FileOutputStream outputStream = new FileOutputStream(fileName);
            outputStream.write(data);
            outputStream.close();
        }
         
    }
    
    /**
     * 读取url中数据,并以字节的形式返回
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static byte[] readStream(InputStream inputStream) throws Exception{
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while((len = inputStream.read(buffer)) !=-1){
            outputStream.write(buffer, 0, len);
        }
        outputStream.close();
        inputStream.close();
        return outputStream.toByteArray();
    }

 

转载于:https://www.cnblogs.com/hwaggLee/p/5606307.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值