|
|
package com.platform.utils;
|
|
|
|
|
|
import java.io.File;
|
|
|
import java.io.FileInputStream;
|
|
|
import java.io.FileOutputStream;
|
|
|
import java.io.IOException;
|
|
|
import java.util.Properties;
|
|
|
|
|
|
import org.apache.log4j.Logger;
|
|
|
import org.apache.tools.zip.ZipEntry;
|
|
|
import org.apache.tools.zip.ZipOutputStream;
|
|
|
|
|
|
public class ZipCompressUtils {
|
|
|
private static Logger logger = Logger.getLogger(ZipCompressUtils.class);
|
|
|
|
|
|
public static void zip(File inputFile, String zipFileName) {
|
|
|
|
|
|
Properties pro = System.getProperties();
|
|
|
String osName = pro.getProperty("os.name");
|
|
|
if(osName.contains("Linux")||osName.contains("linux")){
|
|
|
ProcessMyUtil.execCmdWaitAcquiescent("zip -r "+ FileOperateHelper.addLastSeparator(Configs.PACKAGE_DOWNLOAD_PATH) +"package.zip " + FileOperateHelper.addLastSeparator(Configs.PACKAGE_DOWNLOAD_PATH) + Configs.PACKAGE_NAME);
|
|
|
}
|
|
|
else if (osName.contains("Windows") || osName.contains("windows")) {
|
|
|
// windows下压缩:
|
|
|
try {
|
|
|
// 解决中文文件夹名乱码的问题
|
|
|
FileOutputStream fos = new FileOutputStream(new String(zipFileName));
|
|
|
ZipOutputStream zos = new ZipOutputStream(fos); // 将文件输出流与zip输出流接起来
|
|
|
logger.info("压缩-->开始");
|
|
|
zip(zos, inputFile, "");
|
|
|
logger.info("压缩结束");
|
|
|
zos.close();
|
|
|
} catch (Exception e) {
|
|
|
logger.error(e.getStackTrace());
|
|
|
}
|
|
|
}
|
|
|
else {
|
|
|
logger.error(" The current system is not supported \r\n");
|
|
|
}
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
private static void zip(ZipOutputStream zos, File file, String base) {
|
|
|
try {
|
|
|
// 如果句柄是文件夹
|
|
|
if (file.isDirectory()) {
|
|
|
File[] files = file.listFiles(); // 获取文件夹下的子文件或子目录
|
|
|
zos.putNextEntry(new ZipEntry(base + "/"));
|
|
|
logger.info("目录名:" + file.getName() + "|加入ZIP条目:" + base + "/");
|
|
|
base = (base.length() == 0 ? "" : base + "/");
|
|
|
// 遍历目录下的文件
|
|
|
for (int i = 0; i < files.length; i++) {
|
|
|
// 递归进入本方法
|
|
|
zip(zos, files[i], base + files[i].getName());
|
|
|
}
|
|
|
} else { // 如果句柄是文件
|
|
|
if (base == "")
|
|
|
base = file.getName();
|
|
|
zos.putNextEntry(new ZipEntry(base)); // 填入文件句柄
|
|
|
logger.info("文件名:" + file.getName() + "|加入ZIP条目:" + base);
|
|
|
// 开始压缩
|
|
|
// 从文件入流读,写入ZIP 出流
|
|
|
writeFile(zos, file);
|
|
|
}
|
|
|
} catch (Exception e) {
|
|
|
logger.error(e.getStackTrace());
|
|
|
}
|
|
|
}
|
|
|
|
|
|
private static void writeFile(ZipOutputStream zos, File file)
|
|
|
throws IOException {
|
|
|
logger.info("开始压缩" + file.getName());
|
|
|
FileInputStream fis = new FileInputStream(file);
|
|
|
int len;
|
|
|
while ((len = fis.read()) != -1)
|
|
|
zos.write(len);
|
|
|
logger.info("压缩结束");
|
|
|
fis.close();
|
|
|
}
|
|
|
}
|