用于文件的压缩工具类

/**
* 压缩方法
* (可以压缩空的子目录)
*
* @param srcPath 压缩源路径
* @param zipFileName 目标压缩文件
* @return
*/
public static boolean zip(String srcPath, String zipFileName) {
File srcFile = new File(srcPath);
// 扫描所有要压缩的文件
List<File> fileList = getAllFiles(srcFile);
// 缓冲器
byte[] buffer = new byte[512];
ZipEntry zipEntry = null;
// 每次读出来的长度
int readLength = 0;
try {
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileName));
for (File file : fileList) {
// 若是文件,则压缩这个文件
if (file.isFile()) {
zipEntry = new ZipEntry(getRelativePath(srcPath, file));
zipEntry.setSize(file.length());
zipEntry.setTime(file.lastModified());
zipOutputStream.putNextEntry(zipEntry);
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
while ((readLength = inputStream.read(buffer, 0, BUFFER)) != -1) {
zipOutputStream.write(buffer, 0, readLength);
}
inputStream.close();
} else {
//若是目录(即空目录)则将这个目录写入zip条目
zipEntry = new ZipEntry(getRelativePath(srcPath, file) + "/");
zipOutputStream.putNextEntry(zipEntry);
LogUtil.debug(LogType.Server,"dir compressed: " + file.getCanonicalPath() + "/");
}
}
zipOutputStream.close();
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}

/**
* 取的给定源目录下的所有文件及空的子目录
* 递归实现
*
* @param srcFile
* @return
*/
private static List<File> getAllFiles(File srcFile) {
List<File> fileList = new ArrayList<>();
File[] tmp = srcFile.listFiles();

for (int i = 0; i < tmp.length; i++) {

if (tmp[i].isFile()) {
fileList.add(tmp[i]);
System.out.println("add file: " + tmp[i].getName());
}

if (tmp[i].isDirectory()) {
// 若不是空目录,则递归添加其下的目录和文件
if (tmp[i].listFiles().length != 0) {
fileList.addAll(getAllFiles(tmp[i]));
} else {
// 若是空目录,则添加这个目录到fileList
fileList.add(tmp[i]);
System.out.println("add empty dir: " + tmp[i].getName());
}
}
}
return fileList;
}

/**
* 取相对路径
* 依据文件名和压缩源路径得到文件在压缩源路径下的相对路径
*
* @param dirPath 压缩源路径
* @param file
* @return 相对路径
*/
private static String getRelativePath(String dirPath, File file) {
File dir = new File(dirPath);
String relativePath = file.getName();
StringBuilder sb = new StringBuilder(relativePath);
while (true) {
file = file.getParentFile();
if (file == null) {
break;
}
if (file.equals(dir)) {
break;
} else {
sb.append(file.getName()).append("/").append(relativePath);
}
}
return sb.toString();
}