上来先是标准方式的压缩
/**
* 标准方式压缩
* @param zipFileName
* @param inputFile
* @throws Exception
*/
public static void zip(String zipFileName, File inputFile) throws Exception {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
zip(out, inputFile, "");
out.close();
}
/**
* 标准方式压缩
* @param out
* @param f
* @param base
* @throws Exception
*/
private static void zip(ZipOutputStream out, File f, String base) throws Exception {
if (f.isDirectory()) {
File[] fl = f.listFiles();
out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/"));
out.closeEntry();
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < fl.length; i++) {
if(fl[i].getName().indexOf(".zip")==-1){
zip(out, fl[i], base + fl[i].getName());
}
}
}else {
out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
FileInputStream in = new FileInputStream(f);
int b;
while ( (b = in.read()) != -1) {
out.write(b);
}
out.closeEntry()
in.close();
}
}
现在是存储方式压缩
/**
* 按存储方式压缩
* @param zipFileName
* @param inputFile
* @throws Exception
*/
public static void zip_stored(String zipFileName, File inputFile) throws Exception {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
zip_stored(out, inputFile, "");
out.close();
}
/**
* 按存储方式压缩
* @param out
* @param f
* @param base
* @throws Exception
*/
private static void zip_stored(ZipOutputStream out, File f, String base) throws Exception {
out.setMethod(ZipOutputStream.STORED);
if (f.isDirectory()) {
File[] fl = f.listFiles();
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < fl.length; i++) {
if (fl[i].getName().indexOf(".zip") == -1) {
zip_stored(out, fl[i], base + fl[i].getName());
}
}
} else {
ZipEntry entry = new ZipEntry(base);
entry.setMethod(ZipEntry.STORED);
entry.setSize(f.length());
long crc = 0;
crc = calFileCRC32(f);
entry.setCrc(crc);
out.putNextEntry(entry);
FileInputStream in = new FileInputStream(f);
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
out.closeEntry()
in.close();
}
}
public static long calFileCRC32(File file) throws IOException {
FileInputStream fi = new FileInputStream(file);
CheckedInputStream checksum = new CheckedInputStream(fi, new CRC32());
while (checksum.read() != -1) { }
long temp = checksum.getChecksum().getValue();
fi.close();
checksum.close();
return temp;
}
现在进行解释一下
ZipOutputStream类有设置压缩方法以及在压缩方式下使用的压缩级别,zipOutputStream.setMethod(int method)设置用于条目的默认压缩方法。只要没有为单个 ZIP 文件条目指定压缩方法,就使用ZipOutputStream所设置的压缩方法来存储,默认值为 ZipOutputStream.DEFLATED(表示进行压缩存储),还可以设置成STORED(表示仅打包归档存储),此处的存储压缩便是采用仅打包归档存储,即文件大小基本不变。
ZipOutputStream在设置了压缩方法为DEFLATED后,我们还可以进一步使用setLevel(int level)方法来设置压缩级别,压缩级别值为0-9共10个级别(值越大,表示压缩越利害),默认为Deflater.DEFAULT_COMPRESSION=-1。当然我们也可以通过条目ZipEntry的setMethod方法为单个条件设置压缩方法。
out.putNextEntry(new org.apache.tools.zip.ZipEntry(base)); // 创建压缩的子目录 , 将文件夹放入zip中
out.closeEntry() ; // 关闭zip文件中之前打开的项
如果是存储方式压缩的话得设置压缩的类型:
out.setMethod(ZipOutputStream.STORED); //指定为存储方式压缩
参考资料:
http://jiangzhengjun.iteye.com/blog/517186