Java下载多图片

Java下载多图片

 	//imgUrls 图片地址的集合
    public static void downloadPic(List<String> imgUrls, HttpServletResponse response) throws Exception {
   
        ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
        InputStream fis = null;
        try {
   
            String downloadFilename = "aptitude.zip";// 文件的名称
            downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");// 转换中文否则可能会产生乱码
            response.setContentType("application/octet-stream");
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个多线程下载图片Java 实例代码: ```java import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class MultiThreadImageDownloader { public static void main(String[] args) throws Exception { String[] imageUrls = { "https://example.com/image1.jpg", "https://example.com/image2.jpg", "https://example.com/image3.jpg" }; ExecutorService executor = Executors.newFixedThreadPool(imageUrls.length); for (String imageUrl : imageUrls) { executor.execute(new ImageDownloader(imageUrl)); } executor.shutdown(); } private static class ImageDownloader implements Runnable { private String imageUrl; public ImageDownloader(String imageUrl) { this.imageUrl = imageUrl; } @Override public void run() { try { URL url = new URL(imageUrl); InputStream in = url.openStream(); FileOutputStream out = new FileOutputStream(getFileName(imageUrl)); byte[] buffer = new byte[1024]; int length = 0; while ((length = in.read(buffer)) != -1) { out.write(buffer, 0, length); } in.close(); out.close(); System.out.println("Downloaded " + imageUrl); } catch (Exception e) { System.out.println("Error downloading " + imageUrl); } } private String getFileName(String url) { int index = url.lastIndexOf("/"); return "image" + url.substring(index); } } } ``` 该程序会并发下载多张图片,并将每张图片保存到本地文件系统中。该程序使用了 Java 的线程池 ExecutorService 来管理多线程。每个任务都是一个 ImageDownloader 对象,它实现了 Runnable 接口并重写了 run() 方法。在 run() 方法中,程序会从指定的 URL 中读取图片数据,并将数据写入到本地文件中。最后,程序会输出成功下载图片的 URL。 该程序的运行结果如下: ``` Downloaded https://example.com/image1.jpg Downloaded https://example.com/image3.jpg Downloaded https://example.com/image2.jpg ``` 可以看到,三张图片都被成功下载并保存到本地文件系统中。该程序可以根据实际需要进行修改和优化,例如增加异常处理机制、设置超时时间、使用线程池等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值