今天跟大家聊聊使用ZipOutputStream打包下载,我下面是使用ant的jar打包的,因为他对应中文的支持比较好
大家也可以使用java.util.zip包里面的工具类打包,但是他对于中文不友好,很多都是乱码的(包括注释、文件名、打包名)
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
/**
* 打包下载
*
* @param response
*/
private void downFile(HttpServletResponse resp,
ArrayList<String> filePathList) throws ServletException,
IOException {
// 头文件
resp.setContentType("APPLICATION/OCTET-STREAM");
resp.setHeader("Content-Disposition",
"attachment; filename=" + this.getZipFilename());
// 压缩文件
ZipOutputStream zos = new ZipOutputStream(resp.getOutputStream());
// --拼装
ArrayList<File> fileList = new ArrayList<File>();
for (int i = 0; i < filePathList.size(); i++) {
File file = new File(filePathList.get(i));
fileList.add(file);
}
File[] files = fileList.toArray(new File[fileList.size()]);
// --打包
zipFile(files, "", zos);
zos.flush();
zos.close();
}
/** * 打包文件 * * @param subs * 文件数组 * @param baseName * 自定义名字 * @param zos * 输出流 * @throws IOException */private void zipFile(File[] subs, String baseName, ZipOutputStream zos)throws IOException {for (int i = 0; i < subs.length; i++) {File f = subs[i];zos.putNextEntry(new ZipEntry(baseName + f.getName()));FileInputStream fis = new FileInputStream(f);byte[] buffer = new byte[1024];int r = 0;while ((r = fis.read(buffer)) != -1) {zos.write(buffer, 0, r);}fis.close();}}/** * 压缩包名字 * * @return */private String getZipFilename() {Date date = new Date();String s = date.getTime() + ".zip";return s;}