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

2014-11-24 09:56:24 · 作者: · 浏览: 6
// 获取压缩条目名,初始时将要压缩的文件或目录的相对路径
String entryName = sourceFile.getAbsolutePath().substring(prefixDir.length() + File.separator.length());
// 判断是文件还是目录,如果是目录,则继续迭代压缩
if (sourceFile.isDirectory()) {
// 如果是目录,则需要在目录后面加上分隔符('/')
//ZipEntry zipEntry = new ZipEntry(entryName + File.separator);
//zos.putNextEntry(zipEntry);
// 获取目录中的文件,然后迭代压缩
File[] srcFiles = sourceFile.listFiles();
for (int i = 0; i < srcFiles.length; i++) {
// 压缩
compressRecursive(zos, bout, srcFiles[i], prefixDir);
}
} else {
// 开始写入新的ZIP文件条目并将流定位到条目数据的开始处
ZipEntry zipEntry = new ZipEntry(entryName);
// 向压缩流中写入一个新的条目
zos.putNextEntry(zipEntry);
// 读取将要压缩的文件的输入流
BufferedInputStream bin = null;
try{
// 获取输入流读取文件
bin = new BufferedInputStream(new FileInputStream(sourceFile));
// 读取文件,并写入压缩流
byte[] buffer = new byte[1024];
int readCount = -1;
while ((readCount = bin.read(buffer)) != -1) {
bout.write(buffer, 0, readCount);
}
// 注,在使用缓冲流写压缩文件时,一个条件完后一定要刷新,不然可能有的内容就会存入到后面条目中去了
bout.flush();
// 关闭当前ZIP条目并定位流以写入下一个条目
zos.closeEntry();
} finally {
if (bin != null) {
try { bin.close(); } catch (IOException e) {}
}
}
}
}

/**
* @Description:
* 解压文件
* @param zipPath 被压缩文件,请使用绝对路径
* @param targetPath 解压路径,解压后的文件将会放入此目录中,请使用绝对路径
* 默认为压缩文件的路径的父目录为解压路径
* @param encoding 解压编码
*/
public static void decompress(String zipPath, String targetPath, String encoding)
throws FileNotFoundException, ZipException, IOException {
// 获取解缩文件
File file = new File(zipPath);
if (!file.isFile()) {
throw new FileNotFoundException("要解压的文件不存在");
}
// 设置解压路径
if (targetPath == null || "".equals(targetPath)) {
targetPath = file.getParent();
}
// 设置解压编码
if (encoding == null || "".equals(encoding)) {
encoding = "GBK";
}
// 实例化ZipFile对象
ZipFile zipFile = new ZipFile(file, encoding);
// 获取ZipFile中的条目
Enumeration files = zipFile.getEntries();
// 迭代中的每一个条目
ZipEntry entry = null;
// 解压后的文件
File outFile = null;
// 读取压缩文件的输入流
BufferedInputStream bin = null;
// 写入解压后文件的输出流
BufferedOutputStream bout = null;
while (files.hasMoreElements()) {
// 获取解压条目
entry = files.nextElement();
// 实例化解压后文件对象
outFile = new File(targetPath + File.separator + entry.getName());
// 如果条目为目录,则跳向下一个
if (entry.getName().endsWith(File.separator)) {
outFile.mkdirs();
continue;
}
// 创建目录
if (!outFile.getParentFile().exists()) {