package com.zwc.www.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
* 支持zip的压缩,zip的解压
*/
public class OperateZip {
private File sourceFile;
private File destFile;
/**
* 压缩文件
*/
public void zip(){
try {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(this.destFile));
FileInputStream fis = null;
ZipEntry ze = null;
File[] files = this.sourceFile.listFiles();
int length = 0;
byte[] b = new byte[1024];
for(int i = 0; i < files.length; i ++){
File file = files[i];
fis = new FileInputStream(file);
this.process(file);
ze = new ZipEntry(file.getName());
zos.putNextEntry(ze);
while((length = fis.read(b)) != -1){
zos.write(b, 0, length);
}
}
fis.close();
zos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 解压文件
*/
public void unzip(){
try {
ZipFile sourceZipFile = new ZipFile(this.sourceFile);
InputStream zis = null;
@SuppressWarnings("unchecked")
Enumeration<ZipEntry> e = (Enumeration<ZipEntry>) sourceZipFile.entries();
FileOutputStream fos = null;
ZipEntry ze = null;
int length = 0;
byte[] b = new byte[1024];
while(e.hasMoreElements()){
ze = e.nextElement();
zis = sourceZipFile.getInputStream(ze);
File file = new File(this.destFile,ze.getName());
fos = new FileOutputStream(file);
while((length = zis.read(b)) != -1){
fos.write(b, 0, length);
}
fos.flush();
fos.close();
}
zis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 中间处理过程
*/
public File process(File file){
return file;
}
/**
* 设置压缩文件存放位置和压缩文件名
*/
public void setZipFile(String sourceDir, String zipDir, String zipFileName){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
String date = sdf.format(new Date());
zipFileName = "".equals(zipFileName)? date + ".zip" : zipFileName;
if(zipDir.lastIndexOf(File.separator) == zipDir.length() - 1){
this.destFile = new File(zipDir + zipFileName);
}else{
this.destFile = new File(zipDir + File.separator + zipFileName);
}
this.sourceFile = new File(sourceDir);
}
/**
* 设置解压文件存放位置
*/
public void setUnzipDir(String sourceFile ,String unzipDir){
this.sourceFile = new File(sourceFile);
if(unzipDir.lastIndexOf(File.separator) == unzipDir.length() - 1){
this.destFile = new File(unzipDir);
}else{
this.destFile = new File(unzipDir + File.separator);
}
this.destFile = new File(unzipDir);
}
public static void main(String[] args) {
OperateZip oz = new OperateZip();
oz.setZipFile("C://key", "C://", "");
oz.zip();
/*oz.setUnzipDir("c://2010-12-09 16_17_03.zip", "C://key_bak");
oz.unzip();*/
}
}