压缩和解压的工具类(ant-1.8.4.jar)(二)

2014-11-24 09:56:24 · 作者: · 浏览: 1
ing);
// 设置压缩包注释
zos.setComment(comment);
// 启用压缩
zos.setMethod(ZipOutputStream.DEFLATED);
// 设置压缩级别为最强压缩
zos.setLevel(Deflater.BEST_COMPRESSION);
// 压缩文件缓冲流
BufferedOutputStream bout = null;
try {
// 封装压缩流为缓冲流
bout = new BufferedOutputStream(zos);
// 对数据源进行压缩
compressRecursive(zos, bout, sourceFile, sourceFile.getParent());
} finally {
if (bout != null) {
try{ bout.close(); } catch (Exception e) {}
}
}
}

/**
* @Description:
* 压缩文件,支持将多个文件或目录压缩到同一个压缩文件中
* @param sourcePath 将要压缩的文件或目录的路径的集合,请使用绝对路径
* @param zipPath 生成压缩文件的路径,请使用绝对路径。该路不能为空,并且必须以“.zip”为结尾
* @param encoding 压缩编码
* @param comment 压缩注释
*/
public static void compress(List sourcePaths, String zipPath, String encoding, String comment)
throws FileNotFoundException, IOException {
// 设置压缩文件路径,默认为将要压缩的路径的父目录为压缩文件的父目录
if (zipPath == null || "".equals(zipPath) || !zipPath.endsWith(".zip")) {
throw new FileNotFoundException("必须指定一个压缩路径,而且该路径必须以'.zip'为结尾");
}
// 设置解压编码
if (encoding == null || "".equals(encoding)) {
encoding = "GBK";
}
// 要创建的压缩文件的父目录不存在,则创建
File zipFile = new File(zipPath);
if (!zipFile.getParentFile().exists()) {
zipFile.getParentFile().mkdirs();
}
// 创建压缩文件输出流
FileOutputStream fos = null;
try {
fos = new FileOutputStream(zipPath);
} catch (FileNotFoundException e) {
if (fos != null) {
try{ fos.close(); } catch (Exception e1) {}
}
}
// 使用指定校验和创建输出流
CheckedOutputStream csum = new CheckedOutputStream(fos, new CRC32());
// 创建压缩流
ZipOutputStream zos = new ZipOutputStream(csum);
// 设置编码,支持中文
zos.setEncoding(encoding);
// 设置压缩包注释
zos.setComment(comment);
// 启用压缩
zos.setMethod(ZipOutputStream.DEFLATED);
// 设置压缩级别为最强压缩
zos.setLevel(Deflater.BEST_COMPRESSION);
// 压缩文件缓冲流
BufferedOutputStream bout = null;
try {
// 封装压缩流为缓冲流
bout = new BufferedOutputStream(zos);
// 迭代压缩每一个路径
for (int i=0,len=sourcePaths.size(); i // 获取每一个压缩路径
File sourceFile = new File(sourcePaths.get(i));
// 对数据源进行压缩
compressRecursive(zos, bout, sourceFile, sourceFile.getParent());
}
} finally {
if (bout != null) {
try{ bout.close(); } catch (Exception e) {}
}
}
}

/**
* @Description:
* 压缩文件时,所使用的迭代方法
* @param zos 压缩输出流
* @param bout 封装压缩输出流的缓冲流
* @param sourceFile 将要压缩的文件或目录的路径
* @param prefixDir 整个将要压缩的文件或目录的父目录,传入此值为了获取压缩条目的名称
*/
private static void compressRecursive(ZipOutputStream zos, BufferedOutputStream bout,
File sourceFile, String prefixDir) throws IOException, FileNotFoundException {