admin管理员组文章数量:1639934
引入依赖:zip4j
<dependency>
<groupId>net.lingala.zip4j</groupId>
<artifactId>zip4j</artifactId>
<version>1.3.2</version>
</dependency>
一、压缩
不多说直接上图,如下图为我测试的文件路径。
桌面上的“测试加密压缩”文件夹下,一个为文件,一个为文件夹。
public class Test {
public static void main(String[] args) throws ZipException {
compressedFileWithPassword("C:/Users/12495/Desktop/测试加密压缩",
"C:/Users/12495/Desktop/测试加密压缩","123456");
}
/**
* 压缩包加密
*
* @param resourcesPath 需要压缩的源文件路径
* @param targetPath 压缩后的目标路径
* @param password 压缩密码
* @throws ZipException
*/
public static void compressedFileWithPassword(String resourcesPath, String targetPath, String password) throws ZipException {
File resourcesFile = new File(resourcesPath);
// 没有目标目录为父路径
if (StringUtils.isBlank(targetPath)) {
targetPath = resourcesFile.getParent();
}
File targetFile = new File(targetPath);
//如果目的路径不存在,则新建
if (!targetFile.exists()) {
targetFile.mkdirs();
}
ZipFile zipFile = new ZipFile(resourcesPath + ".zip");
//设置编码
zipFile.setFileNameCharset("GBK");
//设置参数
ZipParameters parameters = new ZipParameters();
//设置压缩方式.
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
//设置压缩级别,默认为0(即不压缩)
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
//设置压缩密码(至少3步)
//设置加密文件
parameters.setEncryptFiles(true);
//设置加密方式
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
if (StringUtils.isNotBlank(password)) {
parameters.setPassword(password);
}
File[] fs = resourcesFile.listFiles();
for (File f : fs) {
if (f.isDirectory()) {
//添加文件夹
zipFile.addFolder(f, parameters);
} else {
//添加文件
zipFile.addFile(f, parameters);
}
}
}
}
压缩后效果图:
成功加密压缩。
二、解压
解压就比较简单了,路径对就没问题了
public class Test {
public static void main(String[] args) throws Exception {
// compressedFileWithPassword("C:/Users/12495/Desktop/测试加密压缩",
// "C:/Users/12495/Desktop/测试加密压缩","123456");
zipUncompressPassword("C:/Users/12495/Desktop/测试加密压缩.zip", "123456");
}
/**
* 解压缩
* @param inputFile 压缩包的路径
* @throws Exception
*/
public static void zipUncompressPassword(String inputFile, String password) throws Exception {
File file = new File(inputFile);
ZipFile zipFile = new ZipFile(file);
//设置文件编码,根据实际场景
zipFile.setFileNameCharset("GBK");
if (zipFile.isEncrypted()) {
zipFile.setPassword(password.toCharArray());
}
zipFile.extractAll(inputFile.replace(".zip", ""));
}
}
以上就是解压的过程。
版权声明:本文标题:Zip4j 压缩包加密压缩与解压 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dianzi/1729295910a1194715.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论