package com.smilezl.crawl.zip;java
import java.io.File;eclipse
import java.io.FileInputStream;ide
import java.io.FileOutputStream;spa
import java.io.IOException;ip
import java.util.zip.CRC32;get
import java.util.zip.ZipEntry;input
import java.util.zip.ZipOutputStream;animation
public class ApacheTarTest {it
/**io
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
String destDir = "E:\\myeclipse_workspace\\bootanimation111111111111.zip";
String dir = "E:\\myeclipse_workspace\\bootanimation";
zip(dir, destDir);
}
/**
* zip
* @param inputFileName 輸入一個文件夾
* @param zipFileName 輸出一個壓縮文件夾,打包後文件名字
* @throws Exception
*/
public static void zip(String inputFileName, String zipFileName){
zip(zipFileName, new File(inputFileName));
}
private static void zip(String zipFileName, File inputFile){
ZipOutputStream zos;
try {
zos = new ZipOutputStream(new FileOutputStream(zipFileName));
zos.setMethod(ZipOutputStream.STORED);
writeZip(zos, inputFile, "");
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* write zip
* @param file
* @param parentPath
* @param out
*/
public static void writeZip(ZipOutputStream zos, File f, String base) {
CRC32 crc = new CRC32();
if (f.isDirectory()) { //判斷是否爲目錄
File[] fl = f.listFiles();
try {
File file = new File(base + "/");
ZipEntry ze = new ZipEntry(base + "/");
crc.reset();
ze.setCrc(crc.getValue());
//ze.setSize(file.length());
ze.setSize(0);
ze.setTime(System.currentTimeMillis());
zos.putNextEntry(ze);
} catch (IOException e) {
e.printStackTrace();
}
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < fl.length; i++) {
writeZip(zos, fl[i], base + fl[i].getName());
}
} else { //壓縮目錄中的全部文件
try {
System.out.println(f);
FileInputStreamin = new FileInputStream(f);
byte[] buffer = new byte[(int) f.length()];
in.read(buffer, 0, (int) f.length());
ZipEntry ze = new ZipEntry(base);
crc.reset();
crc.update(buffer);
ze.setCrc(crc.getValue());
ze.setSize(f.length());
ze.setTime(System.currentTimeMillis());
zos.putNextEntry(ze);
in.close();
zos.write(buffer, 0, buffer.length);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}