java多文件压缩包zip文件下载

/**
 * 下载脚本文件
 * @date 2018/5/16 17:26
 * @since JDK 1.8
 * @author NetSnake
 * @verison: 1.0
 */
@Override
public void fileDownload(ScriptQueryRequest reqMsg, User user,HttpServletResponse response) {
   //参数验证
   ValidationUtils.checkNotEmpty(reqMsg.getScript_id(), "脚本id不能为空");

   //查询脚本信息
   CapabilityScriptDO scriptDO = iCapabilityScriptDao.getScriptById(reqMsg.getScript_id());
   ValidationUtils.checkNotEmpty(scriptDO, "脚本信息不存在");

   //查询脚本下是否有文件
   CapabilityScriptFileDO scriptFileDO = new CapabilityScriptFileDO();
   scriptFileDO.setScript_id(reqMsg.getScript_id());
   scriptFileDO.setDelete_flag(TestCapabilityDictionary.DELETE_FLAG);
   List<CapabilityScriptFileDO> scriptFileDOList =    iCapabilityScriptDao.queryFilesList(scriptFileDO);
   ValidationUtils.checkNotEmpty(scriptFileDOList, "脚本下不存在文件");

   try {
      //压缩文件
      List<File> files = new ArrayList<>();
      for (CapabilityScriptFileDO vo : scriptFileDOList) {

         //读取服务器文件
         String str = vo.getFile_path().replace(downBaseUrl,uploadBaseRealPath);
         System.out.print(str+"=="+vo.getFile_path());
         File file = new File(str);
         files.add(file);
      }

      String fileName = scriptDO.getScript_name() + ".zip";
      //在服务器端创建打包下载的临时文件
      String globalUploadPath = uploadBaseRealPath;
      String outFilePath = globalUploadPath + File.separator + fileName;
      File file = new File(outFilePath);
      //文件输出流
      FileOutputStream outStream = new FileOutputStream(file);
      //压缩流
      ZipOutputStream toClient = new ZipOutputStream(outStream);

      //设置压缩文件内的字符编码,不然会变成乱码
      this.zipFile(files, toClient);
      toClient.close();
      outStream.close();
      this.downloadZip(file, response);

   } catch (Exception e) {
      throw new BusinessException(String.valueOf(ServiceStatusCodeConstant.BUSINESS_EXCEPTION),
            "下载脚本文件失败!!");
   }

}

/**
 * 压缩文件列表中的文件
 * @date 2018/5/17 9:38
 * @since JDK 1.8
 * @author NetSnake
 * @verison: 1.0
 */
public static void zipFile(List files, ZipOutputStream outputStream) {
   try {
      int size = files.size();
      //压缩列表中的文件
      for (int i = 0; i < size; i++) {
         File file = (File) files.get(i);
         try {
            zipFile(file, outputStream);
         } catch (Exception e) {
            continue;
         }
      }
   } catch (Exception e) {
      throw new BusinessException(String.valueOf(ServiceStatusCodeConstant.BUSINESS_EXCEPTION),
            "压缩文件列表中的文件失败!!");
   }
}

/**
 * 将文件写入到zip文件中
 * @date 2018/5/17 9:38
 * @since JDK 1.8
 * @author NetSnake
 * @verison: 1.0
 */
public static void zipFile(File inputFile, ZipOutputStream outputstream) throws IOException, ServletException {
   try {
      if (inputFile.exists()) {
         if (inputFile.isFile()) {
            FileInputStream inStream = new FileInputStream(inputFile);
            BufferedInputStream bInStream = new BufferedInputStream(inStream);
            ZipEntry entry = new ZipEntry(inputFile.getName());
            outputstream.putNextEntry(entry);

            final int MAX_BYTE = 10 * 1024 * 1024;    //最大的流为10M
            long streamTotal = 0;                      //接受流的容量
            int streamNum = 0;                      //流需要分开的数量
            int leaveByte = 0;                      //文件剩下的字符数
            byte[] inOutbyte;                          //byte数组接受文件的数据

            streamTotal = bInStream.available();                        //通过available方法取得流的最大字符数
            streamNum = (int) Math.floor(streamTotal / MAX_BYTE);    //取得流文件需要分开的数量
            leaveByte = (int) streamTotal % MAX_BYTE;                //分开文件之后,剩余的数量

            if (streamNum > 0) {
               for (int j = 0; j < streamNum; ++j) {
                  inOutbyte = new byte[MAX_BYTE];
                  //读入流,保存在byte数组
                  bInStream.read(inOutbyte, 0, MAX_BYTE);
                  outputstream.write(inOutbyte, 0, MAX_BYTE);  //写出流
               }
            }
            //写出剩下的流数据
            inOutbyte = new byte[leaveByte];
            bInStream.read(inOutbyte, 0, leaveByte);
            outputstream.write(inOutbyte);
            outputstream.closeEntry();     //Closes the current ZIP entry and positions the stream for writing the next entry
            bInStream.close();    //关闭
            inStream.close();
         }
      } else {
         throw new BusinessException(String.valueOf(ServiceStatusCodeConstant.BUSINESS_EXCEPTION),
               "zip文件不存在!!");
      }
   } catch (IOException e) {
      throw new BusinessException(String.valueOf(ServiceStatusCodeConstant.BUSINESS_EXCEPTION),
            "将文件写入到zip文件中失败!!");
   }
}

/**
 * 下载打包的文件
 * @date 2018/5/17 9:39
 * @since JDK 1.8
 * @author NetSnake
 * @verison: 1.0
 */
public static void downloadZip(File file, HttpServletResponse response) {
   try {
      // 以流的形式下载文件。
      BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
      byte[] buffer = new byte[fis.available()];
      fis.read(buffer);
      fis.close();
      // 清空response
      response.reset();

      OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
      response.setContentType("application/octet-stream");
      response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
      toClient.write(buffer);
      toClient.flush();
      toClient.close();
      file.delete();        //将生成的服务器端文件删除
   } catch (IOException ex) {
      throw new BusinessException(String.valueOf(ServiceStatusCodeConstant.BUSINESS_EXCEPTION),
            "下载打包的文件失败!!");
   }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 可以通过使用 ZipOutputStream 类来将多个文件压缩成一个 zip 压缩包,具体实现步骤如下: 1. 创建一个 FileOutputStream 对象,并通过 ZipOutputStream 的构造函数创建一个 ZipOutputStream 对象,将 FileOutputStream 对象作为参数传入。 ```java FileOutputStream fos = new FileOutputStream("test.zip"); ZipOutputStream zos = new ZipOutputStream(fos); ``` 2. 创建一个 File 对象数组,表示要被压缩文件列表。 ```java File[] files = new File[] { new File("file1.txt"), new File("file2.txt"), new File("file3.txt") }; ``` 3. 遍历文件列表,将每个文件逐个添加到 zip 压缩包中。 ```java for (File file : files) { FileInputStream fis = new FileInputStream(file); ZipEntry ze = new ZipEntry(file.getName()); zos.putNextEntry(ze); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) > 0) { zos.write(buffer, 0, len); } zos.closeEntry(); fis.close(); } ``` 4. 关闭 ZipOutputStream 和 FileOutputStream 对象。 ```java zos.close(); fos.close(); ``` 完整代码示例: ```java import java.io.*; import java.util.zip.*; public class ZipFiles { public static void main(String[] args) throws IOException { FileOutputStream fos = new FileOutputStream("test.zip"); ZipOutputStream zos = new ZipOutputStream(fos); File[] files = new File[] { new File("file1.txt"), new File("file2.txt"), new File("file3.txt") }; for (File file : files) { FileInputStream fis = new FileInputStream(file); ZipEntry ze = new ZipEntry(file.getName()); zos.putNextEntry(ze); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) > 0) { zos.write(buffer, 0, len); } zos.closeEntry(); fis.close(); } zos.close(); fos.close(); } } ``` 运行以上代码,就可以将 file1.txt、file2.txt 和 file3.txt 三个文件压缩成一个 test.zip 压缩包
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值