package com.cvicse.bankface.sd.util;
import java.io.*;
import org.apache.tools.zip.*;
import java.util.Enumeration;
/**
* 实现文件的压缩解压(.zip)
*/
public class AntZip {
private ZipFile zipFile;
private ZipOutputStream zipOut; // 压缩Zip
private ZipEntry zipEntry;
private static int bufSize; // size of bytes
private byte[] buf;
private int readedBytes;
public AntZip() {
this(512);
}
public AntZip(int bufSize) {
this.bufSize = bufSize;
this.buf = new byte[this.bufSize];
}
/**
* 压缩指定文件
*
* @param fileName
* 要压缩的文件名
* @param zipFileName
* 压缩后生成的zip文件名
*/
public void doZip(String fileName, String zipFileName) {// fileName:需要压缩的文件名
File zipDir;
zipDir = new File(fileName);
try {
File file = new File(zipFileName);
// 如果指定文件的目录不存在,则创建之.
File parent = file.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
this.zipOut = new ZipOutputStream(new BufferedOutputStream(
new FileOutputStream(zipFileName)));
handleDir(zipDir, this.zipOut);
this.zipOut.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
// 由doZip调用,写入压缩文件
private void handleDir(File fileName, ZipOutputStream zipOut)
throws IOException {
FileInputStream fileIn;
fileIn = new FileInputStream(fileName);//要压缩的文件
int beginIndex = fileName.toString().lastIndexOf("\\") + 1;
String zipFileName = fileName.toString().substring(beginIndex);
this.zipOut.putNextEntry(new ZipEntry(zipFileName));
while ((this.readedBytes = fileIn.read(this.buf)) > 0) {
this.zipOut.write(this.buf, 0, this.readedBytes);
}
this.zipOut.closeEntry();
}
// 解压指定zip文件
public void unZip(String absoluteFromFileName, String absoluteToDirectory) {// 需要解压的zip文件名
FileOutputStream fileOut;
File file;
InputStream inputStream;
try {
this.zipFile = new ZipFile(absoluteFromFileName);
for (Enumeration entries = this.zipFile.getEntries(); entries
.hasMoreElements();) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String name = entry.getName();
String absoluteUnZipFileName = absoluteToDirectory+ name;// 解压后的文件绝对路径
file = new File(absoluteUnZipFileName);
if (entry.isDirectory()) {
file.mkdirs();
} else {
// 如果指定文件的目录不存在,则创建之.
File parent = file.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
inputStream = zipFile.getInputStream(entry);
fileOut = new FileOutputStream(file);
while ((this.readedBytes = inputStream.read(this.buf)) > 0) {
fileOut.write(this.buf, 0, this.readedBytes);
}
fileOut.close();
inputStream.close();
}
}
this.zipFile.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
// 设置缓冲区大小
public void setBufSize(int bufSize) {
this.bufSize = bufSize;
}
}