package com.unis.io;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipUtil {
private static int BUFFER_SIZE = 2048;
private static byte[] BUFFER_DATA = new byte[BUFFER_SIZE];
/**
* 压缩
* @param src 源路径
* @param desc 目标路径
* @throws IOException
*/
public static void zip(String src, String dest) throws IOException {
ZipOutputStream bos = null;
try {
File f = new File(src);
dest = dest + File.separator + f.getName() + ".zip";
bos = new ZipOutputStream(new BufferedOutputStream(
new FileOutputStream(new File(dest))));
if (f.isFile()) {
zipFile(bos, f, null);
} else {
zipDir(bos, f, null);
}
} finally {
if (bos != null)
bos.close();
}
}
private static void zipDir(ZipOutputStream zos, File dir, String parentPath) throws IOException {
String path = parentPath==null?dir.getName():parentPath+File.separator+dir.getName();
for(File f : dir.listFiles()){
if(f.isFile()){
zipFile(zos,f,path);
}else{
zipDir(zos,f,path);
}
}
}
private static void zipFile(ZipOutputStream zos, File f, String path)
throws IOException {
ZipEntry zn = new ZipEntry(path + File.separator + f.getName());
zos.putNextEntry(zn);
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(new FileInputStream(f), BUFFER_SIZE);
int l = 0;
while ((l = bis.read(BUFFER_DATA)) != -1) {
zos.write(BUFFER_DATA, 0, l);
}
} finally {
if (bis != null)
bis.close();
}
}
public static void main(String[] args) {
try {
zip("E:/java/a","E:/java");
} catch (IOException e) {
e.printStackTrace();
}
}
}