package com.moon.server.helper;
|
|
import net.lingala.zip4j.ZipFile;
|
import net.lingala.zip4j.exception.ZipException;
|
import net.lingala.zip4j.model.ZipParameters;
|
import net.lingala.zip4j.model.enums.AesKeyStrength;
|
import net.lingala.zip4j.model.enums.CompressionLevel;
|
import net.lingala.zip4j.model.enums.CompressionMethod;
|
import net.lingala.zip4j.model.enums.EncryptionMethod;
|
import org.apache.commons.logging.Log;
|
import org.apache.commons.logging.LogFactory;
|
|
import java.io.File;
|
import java.nio.charset.StandardCharsets;
|
|
@SuppressWarnings("ALL")
|
public class Zip4jHelper {
|
private final static Log log = LogFactory.getLog(Zip4jHelper.class);
|
|
public static boolean zip(String zipFile, String sourcePath, String pwd) {
|
try {
|
ZipFile zip = StringHelper.isEmpty(pwd) ? new ZipFile(zipFile) : new ZipFile(zipFile, pwd.toCharArray());
|
zip.setCharset(StandardCharsets.UTF_8);
|
|
File f = zip.getFile();
|
if (!f.getParentFile().exists()) {
|
f.getParentFile().mkdirs();
|
}
|
if (f.exists()) {
|
f.delete();
|
}
|
|
ZipParameters params = getZipParams(!StringHelper.isEmpty(pwd));
|
|
File currentFile = new File(sourcePath);
|
if (currentFile.isDirectory()) {
|
zip.addFolder(currentFile, params);
|
} else {
|
zip.addFile(currentFile, params);
|
}
|
|
return true;
|
} catch (Exception ex) {
|
log.error(ex.getMessage(), ex);
|
return false;
|
}
|
}
|
|
public static ZipFile createZipFile(String zipFile, String pwd) {
|
try {
|
ZipFile zip = StringHelper.isEmpty(pwd) ? new ZipFile(zipFile) : new ZipFile(zipFile, pwd.toCharArray());
|
// zip.setCharset(Charset.forName("GBK"))
|
zip.setCharset(StandardCharsets.UTF_8);
|
|
File f = zip.getFile();
|
if (!f.getParentFile().exists()) {
|
f.getParentFile().mkdirs();
|
}
|
if (f.exists()) {
|
f.delete();
|
}
|
|
return zip;
|
} catch (Exception ex) {
|
log.error(ex.getMessage(), ex);
|
return null;
|
}
|
}
|
|
public static ZipParameters getZipParams(boolean hasPwd) {
|
ZipParameters params = new ZipParameters();
|
params.setCompressionMethod(CompressionMethod.DEFLATE);
|
params.setCompressionLevel(CompressionLevel.MAXIMUM);
|
|
if (hasPwd) {
|
params.setEncryptFiles(true);
|
params.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_128);
|
params.setEncryptionMethod(EncryptionMethod.AES);
|
}
|
|
return params;
|
}
|
|
private static void addZipFile(ZipFile zip, ZipParameters params, File file) throws ZipException {
|
if (file.isDirectory()) {
|
File[] files = file.listFiles();
|
for (File f : files) {
|
addZipFile(zip, params, f);
|
}
|
} else {
|
zip.addFile(file, params);
|
}
|
}
|
|
public static boolean unzip(String zipFile, String toPath, String password) {
|
try {
|
ZipFile zip = new ZipFile(zipFile);
|
|
if (!StringHelper.isEmpty(password)) {
|
zip.setPassword(password.toCharArray());
|
}
|
|
zip.extractAll(toPath);
|
|
return true;
|
} catch (Exception ex) {
|
log.error(ex.getMessage(), ex);
|
return false;
|
}
|
}
|
}
|