package com.skycc.util.file;
import java.io.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
* 对文件进行解压缩;
*/
import org.apache.log4j.Logger;
import org.apache.tools.zip.*;
/**
* 用于对文件的压缩和解压;
* @author zhoulexing
* @date:2018年11月21日
*
*/
public class ZIPArchive {
private Logger logger =Logger.getLogger(ZIPArchive.class);
/**使用GBK编码可以避免压缩中文文件名乱码*/
private static final String CHINESE_CHARSET = "GBK";
public ZIPArchive() {
}
/**
* 给定根目录,返回一个相对路径所对应的实际文件名.
*
* @param baseDir
* 指定根目录
* @param absFileName
* 相对路径名,来自于ZipEntry中的name
* @return java.io.File 实际的文件
*/
private static File getRealFileName(String baseDir, String absFileName) {
String[] dirs = absFileName.split("/");
File ret = new File(baseDir);
// 创建目录结构
if (dirs.length > 1) {
for (int i = 0; i < dirs.length - 1; i++) {
ret = new File(ret, dirs[i]);
}
}
if (!ret.exists()) {
ret.mkdirs();
}
ret = new File(ret, dirs[dirs.length - 1]);
return ret;
}
/**
* 给定根目录及文件的实际路径,返回带有相对路径的文件名,用于zip文件中的路径.
* 如将绝对路径,baseDir\dir1\dir2\file.txt改成 dir1/dir2/file.txt
*
* @param baseDir
* java.lang.String 根目录
* @param realFileName
* java.io.File 实际的文件名
* @return 相对文件名
*/
private static String getAbsFileName(String baseDir, File realFileName) {
File real = realFileName;
File base = new File(baseDir);
String ret = real.getName();
while (true) {
real = real.getParentFile();
if (real == null)
break;
if (real.equals(base))
break;
else {
ret = real.getName() + "/" + ret;
}
}
return ret;
}
/**
* 取得指定目录以及其各级子目录下的所有文件的列表,注意,返回的列表中不含目录.
*
* @param baseDir
* File 指定的目录
* @return 包含java.io.File的List
*/
public static List getSubFiles(File baseDir) {
List fileList = new ArrayList();
File[] tmp = baseDir.listFiles();
for (int i = 0; i < tmp.length; i++) {
// 如果是文件,直接加入fileList
if (tmp[i].isFile()) {
fileList.add(tmp[i]);
}
// 如果是目录,递归调用本方法,并将结果集加入fileList
if (tmp[i].isDirectory()) {
fileList.addAll(getSubFiles(tmp[i]));
}
}
return fileList;
}
/**
*
* zip压缩功能测试. 此方法可保留被压缩文件的目录结构 注意是压缩文件夹。
*
* @param baseDir
* 所要压缩的目录名(包含绝对路径)
* @param objFileName
* 压缩后的文件名
* @throws Exception
*/
public static void createZip(String baseDir, String objFileName) throws Exception {
File folderObject = new File(baseDir);
if (folderObject.exists()) {
List fileList = getSubFiles(new File(baseDir));
// 压缩文件名
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(
objFileName));
ZipEntry ze = null;
byte[] buf = new byte[1024];
int readLen = 0;
for (int i = 0; i < fileList.size(); i++) {
File f = (File) fileList.get(i);
/*
* 创建一个ZipEntry,并设置Name和其它的一些属性
* 注意,该ZipEntry是包含目录结构的,此功能是由getAbsFileName(String,string)完成的
*/
ze = new ZipEntry(getAbsFileName(baseDir, f));
ze.setSize(f.length());
ze.setTime(f.lastModified());
// 将ZipEntry加到zos中,再写入实际的文件内容
zos.putNextEntry(ze);
InputStream is = new BufferedInputStream(new FileInputStream(f));
while ((readLen = is.read(buf, 0, 1024)) != -1) {
zos.write(buf, 0, readLen);
}
is.close();
}
zos.close();
} else {
throw new Exception("this folder isnot exist!");
}
}
/**
* 测试解压缩功能. 将d:\\download\\test.zip连同子目录解压到d:\\temp\\zipout目录下.
*
* @param sourceZip
* 待解压的zip文件
* @param outFileName
* @throws IOException
*/
public static void releaseZipToFile(String sourceZip, String outFileName)
throws IOException {
ZipFile zfile = new ZipFile(sourceZip,CHINESE_CHARSET);
Enumeration zList = zfile.getEntries();
ZipEntry ze = null;
byte[] buf = new byte[1024];
while (zList.hasMoreElements()) {
// 从ZipFile中得到一个ZipEntry
ze = (ZipEntry) zList.nextElement();
if (ze.isDirectory()) {
continue;
}
// 以ZipEntry为参数得到一个InputStream,并写到OutputStream中
InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
OutputStream os = new BufferedOutputStream(new FileOutputStream(
getRealFileName(outFileName, ze.getName())));
int readLen = 0;
while ((readLen = is.read(buf, 0, 1024)) != -1) {
os.write(buf, 0, readLen);
}
is.close();
os.close();
}
zfile.close();
}
/***
* 压缩文件
* @param filePath 文件路径
* @param outPath 输出路径
*/
public void compress(String filePath, String outPath) {
// 创建输入流对象
InputStream in = null;
try {
in = new FileInputStream(filePath);
} catch (FileNotFoundException e) {
logger.error(e.getMessage());
}
// 创建输出流对象
FileOutputStream fileOut = null;
try {
fileOut = new FileOutputStream(outPath);
} catch (FileNotFoundException ex) {
logger.error(ex.getMessage());
}
// 创建ZIP压缩格式的输出流对象
ZipOutputStream zipOut = new ZipOutputStream(fileOut);
// 创建压缩文件进入点对象
ZipEntry zipEntry = new ZipEntry(new File(filePath).getName());
try {
zipOut.putNextEntry(zipEntry);
} catch (IOException ex) {
logger.error(ex.getMessage());
}
// 向压缩文件写入数据
byte b[] = new byte[512];
int len = 0;
try {
while ((len = in.read(b)) != -1) {
zipOut.write(b, 0, len);
}
} catch (IOException ex) {
logger.error(ex.getMessage());
}
// 关闭当前的压缩文件进入点对象
try {
zipOut.closeEntry();
} catch (IOException ex) {
logger.error(ex.getMessage());
}
// 关闭ZIP压缩格式的输出流对象
try {
zipOut.close();
} catch (IOException ex) {
logger.error(ex.getMessage());
}
// 关闭文件输入流
try {
in.close();
} catch (IOException ex) {
logger.error(ex.getMessage());
}
// 关闭文件输出流
try {
fileOut.close();
} catch (IOException ex) {
logger.error(ex.getMessage());
}
}
/***
* 解压缩文件
* @param filePath zip文件路径
* @param outPath 压缩到哪个路径
*/
@SuppressWarnings("unchecked")
public void releaseZIP(String filePath, String outPath) {
try {
// 创建ZIP格式文件
ZipFile zipFile = new ZipFile(filePath);
Enumeration names = zipFile.getEntries();
int bufferSize = 2048;
while (names.hasMoreElements()) {
ZipEntry entry = (ZipEntry) names.nextElement();
if (!entry.isDirectory()) {
InputStream in = zipFile.getInputStrea