java压缩文件或文件夹

/**
* @param inputFilePath
* 压缩 文件或文件夹的绝对路径
* @param outFilePath
* 压缩文件的输出路径
* */
public void zip(String inputFilePath, String outFilePath) throws Exception {
FileOutputStream output = null;
ZipOutputStream zipout = null;
try {
output = new FileOutputStream(outFilePath);
File inputFile = new File(inputFilePath);
if (!inputFile.exists()) {
_log.error(inputFilePath + " not found");
throw new FileNotFoundException(inputFilePath);
}
zipout = new ZipOutputStream(output);
executeZip(zipout, inputFile, "");
} catch (FileNotFoundException ex) {
_log.error(outFilePath + " not found |", ex);
throw new FileNotFoundException(outFilePath);
} finally {
closeStream(output, zipout);
}

}

/** 压缩 文件夹 */
private void executeZip(ZipOutputStream out, File file, String base)
throws Exception {
if (file.isDirectory()) {
File[] array = file.listFiles();
out.putNextEntry(new ZipEntry(base + "/"));
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < array.length; i++) {
executeZip(out, array[i], base + array[i].getName());
}
} else {
zipFile(out, file, base);
}
}


/** 压缩 文件 */
private void zipFile(ZipOutputStream outStream, File file, String base)
throws IOException {
putEntry(outStream, file, base);

FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
int c = 0;
byte[] bt = new byte[SIZE];
while ((c = inputStream.read(bt)) != -1) {
outStream.write(bt, 0, c);
}
} catch (FileNotFoundException ex) {
_log.error(file.getPath() + " not found |", ex);
throw ex;
} catch (IOException e) {
_log.error("IOException in zipFile |", e);
throw e;
} finally {
if (null != inputStream) {
inputStream.close();
}
}
}

private void putEntry(ZipOutputStream outStream, File file, String base)
throws IOException {
if (base.length() > 0) {
outStream.putNextEntry(new ZipEntry(base));
} else {
outStream.putNextEntry(new ZipEntry(file.getName()));
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值