linux tar java zipoutputstream_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();

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值