java多文件压缩成biz

java多文件压缩成biz

废话不多说,代码说话

     //文件地址
     List<String> urls = new ArrayList<>();
     //文件名称
     List<String> name = new ArrayList<>();
     String zipFilePath = "D:/NFC.zip";
     ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFilePath));
        try {
            for (int i = 0; i < urls.size(); i++) {
                String name = names.get(i);
                fileToZip(urls.get(i), zipOut,name );
            }
            // 压缩完成后,关闭压缩流
            zipOut.close();

            //拼接下载默认名称并转为ISO-8859-1格式
            String fileName = new String(("NFC.zip").getBytes(),"ISO-8859-1");
            response.setHeader("Content-Disposition", "attchment;filename="+fileName);

            //该流不可以手动关闭,手动关闭下载会出问题,下载完成后会自动关闭
            ServletOutputStream outputStream = response.getOutputStream();
            FileInputStream inputStream = new FileInputStream(zipFilePath);
            // copy方法为文件复制,在这里直接实现了下载效果
            IOUtils.copy(inputStream, outputStream);

            // 关闭输入流
            inputStream.close();

            //下载完成之后,删掉这个zip包
            File fileTempZip = new File(zipFilePath);
            fileTempZip.delete();
//            map.put("zip",zipFilePath);
//            remoteEpFileService.delZip(map);

        } catch (Exception e) {
            log.info("er",e);
        }


public void fileToZip(String filePath,ZipOutputStream zipOut,String name) throws Exception {



        Map<String,Object> map = new HashMap<>();
        map.put("url",filePath);
        File file = remoteEpFileService.response(map);
        InputStream input = new FileInputStream(file);

//        InputStream fileInput = urlfile.openStream();
        String fileName = name;
//        FileInputStream fileInput = new FileInputStream(filePath);
        // 缓冲
        byte[] bufferArea = new byte[1024 * 10];
        BufferedInputStream bufferStream = new BufferedInputStream(input, 1024 * 10);
        // 将当前文件作为一个zip实体写入压缩流,fileName代表压缩文件中的文件名称
        zipOut.putNextEntry(new ZipEntry(fileName));
        int length = 0;

        while ((length = bufferStream.read(bufferArea, 0, 1024 * 10)) != -1) {
            zipOut.write(bufferArea, 0, length);
        }
        //关闭流
        input.close();
        // 需要注意的是缓冲流必须要关闭流,否则输出无效
        bufferStream.close();
        // 压缩流不必关闭,使用完后再关
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值