通过 apache.commons.compress 压缩和下载文件
通过 apache.commons.compress 压缩和下载文件
为什么使用apache.commons.compress 第三方开源软件,而不用原生jdk的压缩api? 1. 原生api压缩文件后,有些软件打开压缩包,里面的压缩文件的会有中文文件名乱码问题, 比如winrar软件,但是一些国产软件没问题。 具体原因还没深入了解,后面再补充
大家可以通过apache 官网, , 下载apache三方开源压缩包
压缩代码:
package com.download; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.Calendar; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.io.IOUtils; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; public class DownloadTest { @RequestMapping(value = "/download") @ResponseBody public void download(HttpServletRequest request, HttpServletResponse response) { File Files = new File("F:\download");// 需要下载文件 File zipFile = new File("downlaodtmpfile.zip");// 在本地生成临时文件 try { ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new FileOutputStream(zipFile)); ZipArchiveEntry ze; // 将文件写入到文件 if (Files.isDirectory()) { File[] listFiles = Files.listFiles(); for (File file : listFiles) { ze = new ZipArchiveEntry(file.getName()); zos.putArchiveEntry(ze); IOUtils.copy(new FileInputStream(file), zos); zos.closeArchiveEntry();// 关闭当前文件 } } else { ze = new ZipArchiveEntry(Files.getName()); zos.putArchiveEntry(ze); IOUtils.copy(new FileInputStream(Files), zos); zos.closeArchiveEntry();// 关闭当前文件 } // 需要在此处关闭压缩流,否则一些压缩软件无法打开下载的压缩包,比如winrar软件无法打开, 而一些国产压缩软件可以打开 IOUtils.closeQuietly(zos); // 设置下载文件名 SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); String filename = URLEncoder.encode("批量下载文件" + format.format(Calendar.getInstance().getTime()) + ".zip", "UTF-8"); // 设置下载下载头 response.setHeader("Content-Disposition", "attachment; fileName=" + filename); response.setContentType("application/octet-stream; charset=utf-8"); FileCopyUtils.copy(new FileInputStream(zipFile), response.getOutputStream());// 下载文件 } catch (Exception e) { e.printStackTrace(); } finally { if (zipFile != null && zipFile.exists()) { zipFile.delete();// 将临时文件删掉 } } } }