import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
/**
* 打包工具类
*
* @author alon
*
*/
public class ZIPUtil {
private static ZIPUtil zu = null;
/**
* 获取打包工具实例
*
* @return
*/
public static ZIPUtil getInstance() {
if (zu == null)
zu = new ZIPUtil();
return zu;
}
private ZIPUtil() {
}
/**
* 创建打包文件
*
* @param filePath
* @param out
*/
public void CreateZipFile(String filePath, OutputStream out) {
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
zos.setEncoding("GBK");
writeZipFile(new File(filePath), zos, "");
} catch (Exception e) {
} finally {
try {
if (zos != null)
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 写入打包文件
*
* @param f
* @param zos
* @param hiberarchy
*/
public void writeZipFile(File f, ZipOutputStream zos, String hiberarchy) {
if (f.exists()) {
if (f.isDirectory()) {
hiberarchy += f.getName() + "/";
File[] fif = f.listFiles();
for (int i = 0; i < fif.length; i++) {
writeZipFile(fif[i], zos, hiberarchy);
}
} else {
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
ZipEntry ze = new ZipEntry(hiberarchy + f.getName());
zos.putNextEntry(ze);
byte[] b = new byte[1024];
while (fis.read(b) != -1) {
zos.write(b);
b = new byte[1024];
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}