Java实现将文件或者文件夹压缩成zip
- (1)可以压缩文件,也可以压缩文件夹
- (2)同时支持压缩多级文件夹,工具内部做了递归处理
- (3)碰到空的文件夹,也可以压缩
- (4)可以选择是否保留原来的目录结构,如果不保留,所有文件跑压缩包根目录去了,且空文件夹直接舍弃。注意:如果不保留文件原来目录结构,在碰到文件名相同的文件时,会压缩失败。
- (5)代码中提供了2个压缩文件的方法,一个的输入参数为文件夹路径,一个为文件列表,可根据实际需求选择方法。
一、代码
package com.tax.core.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* ZipUtils
* @author ZENG.XIAO.YAN
* @date 2017年11月19日 下午7:16:08
* @version v1.0
*/
public class ZipUtils {
private static final int BUFFER_SIZE = 2 * 1024;
/**
* 压缩成ZIP 方法1
* @param srcDir 压缩文件夹路径
* @param out 压缩文件输出流
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
throws RuntimeException{
long start = System.currentTimeMillis();
ZipOutputStream zos = null ;
try {
zos = new ZipOutputStream(out);
File sourceFile = new File(srcDir);
compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) +" ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils",e);
}finally{
if(zos != null){
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 压缩成ZIP 方法2
* @param srcFiles 需要压缩的文件列表
* @param out 压缩文件输出流
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static void toZip(List<File> srcFiles , OutputStream out)throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null ;
try {
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
byte[] buf = new byte[BUFFER_SIZE];
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1){
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
}
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) +" ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils",e);
}finally{
if(zos != null){
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 递归压缩方法
* @param sourceFile 源文件
* @param zos zip输出流
* @param name 压缩后的名称
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws Exception
*/
private static void compress(File sourceFile, ZipOutputStream zos, String name,
boolean KeepDirStructure) throws Exception{
byte[] buf = new byte[BUFFER_SIZE];
if(sourceFile.isFile()){
// 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
zos.putNextEntry(new ZipEntry(name));
// copy文件到zip输出流中
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1){
zos.write(buf, 0, len);
}
// Complete the entry
zos.closeEntry();
in.close();
} else {
File[] listFiles = sourceFile.listFiles();
if(listFiles == null || listFiles.length == 0){
// 需要保留原来的文件结构时,需要对空文件夹进行处理
if(KeepDirStructure){
// 空文件夹的处理
zos.putNextEntry(new ZipEntry(name + "/"));
// 没有文件,不需要文件的copy
zos.closeEntry();
}
}else {
for (File file : listFiles) {
// 判断是否需要保留原来的文件结构
if (KeepDirStructure) {
// 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
// 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
} else {
compress(file, zos, file.getName(),KeepDirStructure);
}
}
}
}
}
public static void main(String[] args) throws Exception {
/** 测试压缩方法1 */
FileOutputStream fos1 = new FileOutputStream(new File("c:/mytest01.zip"));
ZipUtils.toZip("D:/log", fos1,true);
/** 测试压缩方法2 */
List<File> fileList = new ArrayList<>();
fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/jar.exe"));
fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/java.exe"));
FileOutputStream fos2 = new FileOutputStream(new File("c:/mytest02.zip"));
ZipUtils.toZip(fileList, fos2);
}
}
package com.tax.core.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* ZipUtils
* @author ZENG.XIAO.YAN
* @date 2017年11月19日 下午7:16:08
* @version v1.0
*/
public class ZipUtils {
private static final int BUFFER_SIZE = 2 * 1024;
/**
* 压缩成ZIP 方法1
* @param srcDir 压缩文件夹路径
* @param out 压缩文件输出流
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
throws RuntimeException{
long start = System.currentTimeMillis();
ZipOutputStream zos = null ;
try {
zos = new ZipOutputStream(out);
File sourceFile = new File(srcDir);
compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) +" ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils",e);
}finally{
if(zos != null){
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 压缩成ZIP 方法2
* @param srcFiles 需要压缩的文件列表
* @param out 压缩文件输出流
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static void toZip(List<File> srcFiles , OutputStream out)throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null ;
try {
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
byte[] buf = new byte[BUFFER_SIZE];
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1){
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
}
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) +" ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils",e);
}finally{
if(zos != null){
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 递归压缩方法
* @param sourceFile 源文件
* @param zos zip输出流
* @param name 压缩后的名称
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws Exception
*/
private static void compress(File sourceFile, ZipOutputStream zos, String name,
boolean KeepDirStructure) throws Exception{
byte[] buf = new byte[BUFFER_SIZE];
if(sourceFile.isFile()){
// 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
zos.putNextEntry(new ZipEntry(name));
// copy文件到zip输出流中
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1){
zos.write(buf, 0, len);
}
// Complete the entry
zos.closeEntry();
in.close();
} else {
File[] listFiles = sourceFile.listFiles();
if(listFiles == null || listFiles.length == 0){
// 需要保留原来的文件结构时,需要对空文件夹进行处理
if(KeepDirStructure){
// 空文件夹的处理
zos.putNextEntry(new ZipEntry(name + "/"));
// 没有文件,不需要文件的copy
zos.closeEntry();
}
}else {
for (File file : listFiles) {
// 判断是否需要保留原来的文件结构
if (KeepDirStructure) {
// 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
// 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
} else {
compress(file, zos, file.getName(),KeepDirStructure);
}
}
}
}
}
public static void main(String[] args) throws Exception {
/** 测试压缩方法1 */
FileOutputStream fos1 = new FileOutputStream(new File("c:/mytest01.zip"));
ZipUtils.toZip("D:/log", fos1,true);
/** 测试压缩方法2 */
List<File> fileList = new ArrayList<>();
fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/jar.exe"));
fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/java.exe"));
FileOutputStream fos2 = new FileOutputStream(new File("c:/mytest02.zip"));
ZipUtils.toZip(fileList, fos2);
}
}
二、注意事项
三、如何在javaWeb项目中使用该工具类
if(userList.size() > 0){
/** 下面为下载zip压缩包相关流程 */
HttpServletRequest request = ServletActionContext.getRequest();
FileWriter writer;
/** 1.创建临时文件夹 */
String rootPath = request.getSession().getServletContext().getRealPath("/");
File temDir = new File(rootPath + "/" + UUID.randomUUID().toString().replaceAll("-", ""));
if(!temDir.exists()){
temDir.mkdirs();
}
/** 2.生成需要下载的文件,存放在临时文件夹内 */
// 这里我们直接来10个内容相同的文件为例,但这个10个文件名不可以相同
for (int i = 0; i < 10; i++) {
dataMap.put("userList", userList);
Map<String, String> endMap = new HashMap<>();
endMap.put("user", "老王");
endMap.put("time", "2017-10-10 10:50:55");
dataMap.put("endMap", endMap);
Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
cfg.setServletContextForTemplateLoading(ServletActionContext.getServletContext(), "/ftl");
Template template = cfg.getTemplate("exportExcel.ftl");
writer = new FileWriter(temDir.getPath()+"/excel"+ i +".xls");
template.process(dataMap, writer);
writer.flush();
writer.close();
}
/** 3.设置response的header */
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=excel.zip");
/** 4.调用工具类,下载zip压缩包 */
// 这里我们不需要保留目录结构
ZipUtils.toZip(temDir.getPath(), response.getOutputStream(),false);
/** 5.删除临时文件和文件夹 */
// 这里我没写递归,直接就这样删除了
File[] listFiles = temDir.listFiles();
for (int i = 0; i < listFiles.length; i++) {
listFiles[i].delete();
}
temDir.delete();
}
if(userList.size() > 0){
/** 下面为下载zip压缩包相关流程 */
HttpServletRequest request = ServletActionContext.getRequest();
FileWriter writer;
/** 1.创建临时文件夹 */
String rootPath = request.getSession().getServletContext().getRealPath("/");
File temDir = new File(rootPath + "/" + UUID.randomUUID().toString().replaceAll("-", ""));
if(!temDir.exists()){
temDir.mkdirs();
}
/** 2.生成需要下载的文件,存放在临时文件夹内 */
// 这里我们直接来10个内容相同的文件为例,但这个10个文件名不可以相同
for (int i = 0; i < 10; i++) {
dataMap.put("userList", userList);
Map<String, String> endMap = new HashMap<>();
endMap.put("user", "老王");
endMap.put("time", "2017-10-10 10:50:55");
dataMap.put("endMap", endMap);
Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
cfg.setServletContextForTemplateLoading(ServletActionContext.getServletContext(), "/ftl");
Template template = cfg.getTemplate("exportExcel.ftl");
writer = new FileWriter(temDir.getPath()+"/excel"+ i +".xls");
template.process(dataMap, writer);
writer.flush();
writer.close();
}
/** 3.设置response的header */
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=excel.zip");
/** 4.调用工具类,下载zip压缩包 */
// 这里我们不需要保留目录结构
ZipUtils.toZip(temDir.getPath(), response.getOutputStream(),false);
/** 5.删除临时文件和文件夹 */
// 这里我没写递归,直接就这样删除了
File[] listFiles = temDir.listFiles();
for (int i = 0; i < listFiles.length; i++) {
listFiles[i].delete();
}
temDir.delete();
}
Java实现将文件或者文件夹压缩成zip的更多相关文章
- 【转】Java实现将文件或者文件夹压缩成zip
转自:https://www.cnblogs.com/zeng1994/p/7862288.html package com.guo.utils; import java.io.*; import j ...
- 【转】java导出多个excel表格,并压缩成zip输出
转自:http://blog.csdn.net/qq_14861089/article/details/53169414 感谢作者分享 /** * 导出支付宝批量支付文件excel * * @p ...
- java实现将文件压缩成zip格式
以下是将文件压缩成zip格式的工具类(复制后可以直接使用): zip4j.jar包下载地址:http://www.lingala.net/zip4j/download.php package util ...
- 使用ICSharpZipLib将文件夹压缩为zip文件
序言: 在我接触Git和SVN之前,我最常用的保存数据的办法就是把文件夹压缩成一个zip文件,添加上时间戳.下面是我在学习C#的文件操作之后做的一个练习,使用开源的ICSharpZipLib来 ...
- vue-webpack项目自动打包压缩成zip文件批处理
为什么需要这个? 使用vue框架开发项目,npm run build这个命令会一直用到,如果需要给后端发包,那你还要打包成zip格式的压缩包,特别是项目提测的时候,一天可能要执行重复好几次,所以才有了 ...
- linux下压缩成zip文件解压zip文件
linux zip命令的基本用法是: zip [参数] [打包后的文件名] [打包的目录路径] linux zip命令参数列表: -a 将文件转成ASCII模式 -F 尝试修复损坏 ...
- java 实现Excel压缩成Zip导出
1 概述 在web项目中常见的一种场景就是将文件导出为Excel,但是当需要导出多个Excel时,使用者将频繁操作,这样就严重降低了项目的友好交互性以及易用性,那么怎么才能优雅的解决这个问题呢?笔者今 ...
- asp.net 把图片压缩成zip之后再进行下载
//这是导出的js方法 function fundaochu() { var data = "keyword=GetImageListdaochu&type=daochu&m ...
- PPT文件流转为图片,并压缩成ZIP文件输出到指定目录
实现流程: 接收InputStream流->复制流->InputStream流转为PPT->PPT转为图片->所有图片压缩到一个压缩文件下 注意: 1.PPT文件分为2003和 ...
随机推荐
- jquery chrome中取select 的值一就返回了
在 <div class="controls"> <select class="span2" data-val="true" ...
- POJ 2248 - Addition Chains - [迭代加深DFS]
题目链接:http://bailian.openjudge.cn/practice/2248 题解: 迭代加深DFS. DFS思路:从目前 $x[1 \sim p]$ 中选取两个,作为一个新的值尝试放 ...
- [No000018D]Vim快速注释/取消注释多行的几种方法-Vim使用技巧(2)
在使用Vim进行编程时,经常遇到需要快速注释或取消注释多行代码的场景,Vim教程网根据已有的教程介绍,总结了三种快速注释/取消注释多行代码的方法. 一.使用Vim可视化模式快速注释/取消注释多行 在V ...
- pytorch-MNIST数据模型测试
用pytorch搭建一个DNN网络,主要目的是熟悉pytorch的使用 """ test Function """ import torch ...
- 类的继承和C3算法
在Python的新式类中,方法解析顺序并非是广度优先的算法,而是采用C3算法,只是在某些情况下,C3算法的结果恰巧符合广度优先算法的结果. 可以通过代码来验证下: class NewStyleClas ...
- jQuery 学习笔记(5)(事件绑定与解绑、事件冒泡与事件默认行为、事件的自动触发、自定义事件、事件命名空间、事件委托、移入移出事件)
1.事件绑定: .eventName(fn) //编码效率略高,但部分事件jQuery没有实现 .on(eventName, fn) //编码效率略低,所有事件均可以添加 注意点:可以同时添加多个相同 ...
- 颜色模式、DPI和PPI、位图和矢量图
颜色模式:用于显示和打印图像的颜色模型 RGB:电子设备的颜色 CMYF:印刷的颜色 印刷的图像分辨率大于等于120像素/厘米,300像素每英寸 图像分辨率单位为PPI(每英寸像素Pixel per ...
- 012-mac下shell,zsh,oh-my-zsh,以及插件
1.查看当前shell echo $SHELL 2.查看安装的shell cat /etc/shells 查看可知 /bin/bash /bin/csh /bin/ksh /bin/sh /bin/t ...
- expect-调试模式的使用
1.expect简介 Expect是一种TCL扩展性的语言,主要用于完成系统交互方面的功能,比如SSH.FTP等,这些程序都需要手工与它们进行互动,而使用Expect就可以模拟人手工互动的过程,是一种 ...
- XMLHttpRequest请求被劫持
十几个请求中随机一个转到 <html><head><script language="javascript">setTimeout(" ...