java实现下载多个图片到本地指定目录并指定文件名

本文介绍了一个使用Java编写的批量下载图片的工具类。该工具能够根据提供的图片URL数组和目标路径,将图片下载到指定目录,并支持自定义文件名。通过设置连接超时和读取超时来确保下载过程的稳定性。

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

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Picdownload {
    /**
    * @Title: downloadPicture
    * @Description: 下载图片
    * @param   picurls 多个图片地址     path 图片下载存放目录  fileNames 多个文件名称 数量与图片地址数量保持一致
    * @return void
    * @throws
    */
    public static void downloadPicture(String[] picurls,String path,String[] fileNames) throws IOException {
        try {
            //多个图片下载地址  
            for(int i=0;i<picurls.length;i++) {
                //根据图片地址构建URL
                URL url= new URL(picurls[i]);
                URLConnection conn = url.openConnection();
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(10000);
                conn.connect();
                DataInputStream dataInputStream = new DataInputStream(conn.getInputStream());
                //创建目录和图片
                File pathFile=new File(path);
                File file=new File(path+File.separator+fileNames[i]);
                if(!pathFile.exists()) {
                    pathFile.mkdirs();
                    file.createNewFile();
                }
                if(!file.exists()) {
                    file.createNewFile();
                }
                //通过流复制图片
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                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();
        }
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值