packagecom.example.demo;import java.io.*;importjava.util.ArrayList;importjava.util.Enumeration;importjava.util.List;importjava.util.zip.ZipException;import org.apache.tools.zip.*;public classZipUtil {private static int BUFFERSIZE = 1024;/*** 压缩
*
*@parampaths
*@paramfileName*/
public static void zip(Listpaths, String fileName) {
ZipOutputStream zos= null;try{
zos= new ZipOutputStream(newFileOutputStream(fileName));for(String filePath : paths) {//递归压缩文件
File file = newFile(filePath);
String relativePath=file.getName();if(file.isDirectory()) {
relativePath+=File.separator;
}
zipFile(file, relativePath, zos);
}
}catch(IOException e) {
e.printStackTrace();
}finally{try{if (zos != null) {
zos.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}
}public static voidzipFile(File file, String relativePath, ZipOutputStream zos) {
InputStream is= null;try{if (!file.isDirectory()) {
ZipEntry zp= newZipEntry(relativePath);
zos.putNextEntry(zp);
is= newFileInputStream(file);byte[] buffer = new byte[BUFFERSIZE];int length = 0;while ((length = is.read(buffer)) >= 0) {
zos.write(buffer,0, length);
}
zos.setEncoding("gbk");//解决文件名中文乱码
zos.flush();
zos.closeEntry();
}else{
String tempPath= null;for(File f : file.listFiles()) {
tempPath= relativePath +f.getName();if(f.isDirectory()) {
tempPath+=File.separator;
}
zipFile(f, tempPath, zos);
}
}
}catch(IOException e) {
e.printStackTrace();
}finally{try{if (is != null) {
is.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}
}/*** 解压缩
*
*@paramfileName
*@parampath*/
public static Listunzip(String fileName, String path) {
FileOutputStream fos= null;
InputStream is= null;
List filePaths = new ArrayList();try{
ZipFile zf= new ZipFile(newFile(fileName), "UTF-8");
Enumeration> en=zf.getEntries();while(en.hasMoreElements()) {
ZipEntry zn=(ZipEntry) en.nextElement();if (!zn.isDirectory()) {
is=zf.getInputStream(zn);
File f= new File(path +zn.getName());
File file=f.getParentFile();
file.mkdirs();
fos= new FileOutputStream(path +zn.getName());int len = 0;byte bufer[] = new byte[BUFFERSIZE];while (-1 != (len =is.read(bufer))) {
fos.write(bufer,0, len);
}
fos.close();
filePaths.add(path+zn.getName());
}
}
}catch(ZipException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}finally{try{if (null !=is) {
is.close();
}if (null !=fos) {
fos.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}returnfilePaths;
}
}