java批量下载网络文件输出成zip包

java批量下载网络文件输出成zip包

直接上代码

	@PostMapping("/batchDownload")
    @ApiOperation("网络批量下载")
    public Result batchDownload(HttpServletResponse response, @RequestBody List<DownloadDto> strs) throws Exception {
        List<DownloadDto> certificates = strs;
        if (certificates==null){
            throw new RenException("请先选择文件,在下载!");
        }
        //组装DownloadDto省略
        String nTime = System.currentTimeMillis()+""; //获取当前时间戳
        String filename = nTime + ".zip";
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(bos);
        int l = 0;
        //循环下载
        for (DownloadDto certificate: certificates) {
            l+=1;
            zos.putNextEntry(new ZipEntry(l + certificate.getFileName()));
            String url = certificate.getUrlPath();
            byte[] bytes = downloadUrlToByte(url);
            zos.write(bytes, 0, bytes.length);
            zos.closeEntry();
        }
        zos.close();
        response.setContentType("application/force-download");// 设置强制下载不打开
        response.addHeader("Content-Disposition", "attachment;fileName=" + filename);// 设置文件名
        File saveDri = new File(downloadFilePath);
        if (!saveDri.exists()){
            saveDri.mkdirs();
        }
       // 保存到的文件路径
        File files = new File(downloadFilePath + filename);
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(files));
        out.write(bos.toByteArray());
        out.close();
        return new Result();
    }

    public byte[] readInputStream(InputStream is) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length = -1;
        try {
            while ((length = is.read(buffer)) != -1) {
                baos.write(buffer, 0, length);
            }
            baos.flush();
        } catch (IOException e) {
            e.printStackTrace();
//            log.error("readInputStream IOException", e);
        }
        byte[] data = baos.toByteArray();
        try {
            is.close();
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
//            log.error("IOException", e);
        }
        return data;
    }

    /**
     * 根据文件链接把文件下载下来并且转成字节码
     */
    public byte[] downloadUrlToByte(String downloadUrl) {
        byte[] data = null;
        InputStream is = null;
        HttpURLConnection conn = null;
        try {
            URL url = new URL(downloadUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            // conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(6000);
            is = conn.getInputStream();
            if (conn.getResponseCode() == 200) {
                data = readInputStream(is);
            } else {
                data = null;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
//            log.error("downloadUrlToByte MalformedURLException", e);
        } catch (IOException e) {
            e.printStackTrace();
//            log.error("downloadUrlToByte IOException", e);
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
//                log.error("IOException", e);
            }
            conn.disconnect();
        }
        return data;
    }

博主精品推荐:
1.微软发布激进支出计划:大举投资满足 AI 服务需求
2.国家网信办等七部门联合公布《生成式人工智能服务管理暂行办法》,8 月 15 日起施行
3.马斯克宣布人工智能公司 xAI 正式成立,旨在“了解宇宙的真实本质
4.月份中国采购经理指数公布 制造业采购经理指数继续回升
推荐关注微信公众号:带你了解最前沿的科技资讯:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这个问题需要用到Java的IO流和压缩库。大致思路如下: 1. 读取txt文件中的每一行,获取文件的URL路径。 2. 根据URL路径创建一个URLConnection对象,获取该文件的输入流。 3. 将输入流写入本地的一个文件中,可以用FileOutputStream实现。 4. 遍历完所有的URL路径后,将所有下载文件压缩一个zip,可以用ZipOutputStream实现。 下面是一个简单的实现代码,仅供参考: ```java import java.io.*; import java.net.*; import java.util.zip.*; public class FileDownloader { public static void main(String[] args) throws IOException { String urlFile = "urls.txt"; // 存放URL路径的文件 String downloadDir = "downloads"; // 下载文件存放的目录 String zipFile = "downloads.zip"; // 压缩后的zip // 创建下载目录 File dir = new File(downloadDir); if (!dir.exists()) { dir.mkdir(); } // 读取URL路径文件 BufferedReader reader = new BufferedReader(new FileReader(urlFile)); String line; while ((line = reader.readLine()) != null) { // 创建URL连接 URL url = new URL(line); URLConnection conn = url.openConnection(); // 获取文件名 String fileName = url.getFile(); fileName = fileName.substring(fileName.lastIndexOf('/') + 1); // 创建文件输出流 FileOutputStream fos = new FileOutputStream(new File(downloadDir, fileName)); // 复制输入流到输出流 InputStream is = conn.getInputStream(); byte[] buffer = new byte[4096]; int len; while ((len = is.read(buffer)) != -1) { fos.write(buffer, 0, len); } fos.close(); is.close(); } reader.close(); // 压缩下载文件 FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(fos); for (File file : dir.listFiles()) { byte[] buffer = new byte[4096]; FileInputStream fis = new FileInputStream(file); zos.putNextEntry(new ZipEntry(file.getName())); int len; while ((len = fis.read(buffer)) != -1) { zos.write(buffer, 0, len); } zos.closeEntry(); fis.close(); } zos.close(); fos.close(); } } ``` 注意:实际应用中需要加入异常处理和错误提示等逻辑。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值