java实现zip压缩
import java.io.*;
import java.util.Enumeration;
import java.util.zip.*;
public class ZipUtils {
static final int BUFFER = 8192;
public static void toZip(String srcPath, String dstPath) throws IOException {
File srcFile = new File(srcPath);
File dstFile = new File(dstPath);
if (!srcFile.exists()) {
throw new FileNotFoundException(srcPath + "不存在!");
}
FileOutputStream out = null;
ZipOutputStream zipOut = null;
try {
out = new FileOutputStream(dstFile);
CheckedOutputStream cos = new CheckedOutputStream(out, new CRC32());
zipOut = new ZipOutputStream(cos);
String baseDir = "";
toZip(srcFile, zipOut, baseDir);
} finally {
if (null != zipOut) {
zipOut.close();
out = null;
}
if (null != out) {
out.close();
}
}
}
private static void toZip(File file, ZipOutputStream zipOut, String baseDir) throws IOException {
if (file.isDirectory()) {
toZipDir(file, zipOut, baseDir);
} else {
toZipFile(file, zipOut, baseDir);
}
}
private static void toZipDir(File dir, ZipOutputStream zipOut, String baseDir) throws IOException {
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
toZip(files[i], zipOut, baseDir + dir.getName() + "/");
}
}
private static void toZipFile(File file, ZipOutputStream zipOut, String baseDir) throws IOException {
if (!file.exists()) {
return;
}
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(new FileInputStream(file));
ZipEntry entry = new ZipEntry(baseDir + file.getName());
zipOut.putNextEntry(entry);
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
zipOut.write(data, 0, count);
}
} finally {
if (null != bis) {
bis.close();
}
}
}
public static void unZip(String zipFile, String dstPath) throws IOException {
File pathFile = new File(dstPath);
if (!pathFile.exists()) {
pathFile.mkdirs();
}
ZipFile zip = new ZipFile(zipFile);
for (Enumeration entries = zip.entries(); entries.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String zipEntryName = entry.getName();
InputStream in = null;
OutputStream out = null;
try {
in = zip.getInputStream(entry);
String outPath = (dstPath + "/" + zipEntryName).replaceAll("\\*", "/");
;
File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if (!file.exists()) {
file.mkdirs();
}
if (new File(outPath).isDirectory()) {
continue;
}
out = new FileOutputStream(outPath);
byte[] buf1 = new byte[1024];
int len;
while ((len = in.read(buf1)) > 0) {
out.write(buf1, 0, len);
}
} finally {
if (null != in) {
in.close();
}
if (null != out) {
out.close();
}
}
}
zip.close();
}
public static void main(String[] args) throws Exception {
String sourceFile = "D:\\IdeaProjects\\DEPLOY\\dist";
String unZipFile = "D:\\IdeaProjects\\DEPLOY\\unZipFile.zip";
String toZipFile = "D:\\IdeaProjects\\DEPLOY\\zipFile.zip";
ZipUtils.unZip(unZipFile, sourceFile);
ZipUtils.toZip(sourceFile, toZipFile);
}
}