ZipOutputStream 后台打包数据 使用CRC32

package com.smilezl.crawl.zip;


import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.zip.CRC32;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;


public class ApacheTarTest {

/**

* @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();

}


}

}

}


你可能感兴趣的:(java,CRC32,打包数据)