文件加密压缩、解密解压引用zip4j包
maven引入配置
<dependency>
<groupId>net.lingala.zip4j</groupId>
<artifactId>zip4j</artifactId>
<version>1.3.2</version>
</dependency>
import lombok.extern.log4j.Log4j;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import java.io.*;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
* Description:文件压缩工具
*
* @Author: wtl
* @Date: 2019/1/8 16:08
*/
@Log4j
public class ZipUtil {
/**
* Description:文件下载
*
* @param srcFilePath 源文件
* @param destDir 目标路径
* @return void
* @Author: wtl
* @Date: 2019/1/10 19:32
*/
public static void download(String srcFilePath, String destDir) throws MalformedURLException {
long startTime = System.currentTimeMillis(); //获取开始时间
int byteread = 0;
try {
destDir = destDir.replace("\\","/" );
//创建路径
File file = new File(destDir.substring(0, destDir.lastIndexOf('/')));
if (!file.exists()) {
file.mkdirs();
}
InputStream inputStream = new FileInputStream(srcFilePath);// 文件的存放路径
FileOutputStream outputStream = new FileOutputStream(destDir);
byte[] buffer = new byte[1024];
while ((byteread = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, byteread);
}
inputStream.close();
outputStream.close();
long endTime = System.currentTimeMillis(); //获取结束时间
log.debug("下载花费时间:" + (endTime - startTime) + "ms");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Description:压缩并加密指定文件夹下所有文件
* 4万个文件大概9分钟
*
* @param sourcePath 源文件路径
* @param zipFilePath 目标文件路径
* @param password 加密密码
* @return boolean
* @Author: wtl
* @Date: 2019/1/11 15:24
*/
public static void compressZipFileByPassword(String sourcePath, String zipFilePath, String password) {
long startTime = System.currentTimeMillis(); //获取开始时间
//判断目标文件是否存在,若存在则删除,否则压缩加密会有问题
File file = new File(zipFilePath);
if (file.exists()) {
file.delete();
}
try {
//创建压缩文件
net.lingala.zip4j.core.ZipFile respFile = new net.lingala.zip4j.core.ZipFile(zipFilePath);
//设置压缩文件参数
ZipParameters parameters = new ZipParameters();
//设置压缩方法
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
//设置压缩级别
//DEFLATE_LEVEL_FASTEST - Lowest compression level but higher speed of compression
//DEFLATE_LEVEL_FAST - Low compression level but higher speed of compression
//DEFLATE_LEVEL_NORMAL - Optimal balance between compression level/speed
//DEFLATE_LEVEL_MAXIMUM - High compression level with a compromise of speed
//DEFLATE_LEVEL_ULTRA - Highest compression level but low speed
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
//设置压缩文件加密
parameters.setEncryptFiles(true);
//设置加密方法
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
//设置aes加密强度
parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
//设置密码
parameters.setPassword(password);
//添加文件到压缩文件
/*respFile.addFiles (sourceFileList,parameters);*/
respFile.addFolder(sourcePath, parameters);
} catch (net.lingala.zip4j.exception.ZipException e) {
throw new RuntimeException("压缩并加密文件失败",e.getCause());
}
long endTime = System.currentTimeMillis(); //获取结束时间
log.warn("压缩加密花费时间:" + (endTime - startTime) + "ms");
}
/**
* Description:解压带密码的压缩文件到指定目录
* 4万个文件大概11分钟
*
* @param sourcePath 源文件路径
* @param destDir 指定目录(以"\\"结尾)
* @param password 解密密码
* @return boolean
* @Author: wtl
* @Date: 2019年1月23日 11:44:23
*/
public static void decompressZipFileByPassword(String sourcePath, String destDir, String password) {
long startTime = System.currentTimeMillis(); //获取开始时间
//若指定目录不存在则创建指定目录路径
destDir = destDir.replace("\\","/" );
File file = new File(destDir.substring(0, destDir.lastIndexOf('/')));
if (!file.exists()) {
file.mkdirs();
}
try {
net.lingala.zip4j.core.ZipFile zipFile = new net.lingala.zip4j.core.ZipFile(sourcePath);
zipFile.setPassword(password);
zipFile.extractAll(destDir);
} catch (net.lingala.zip4j.exception.ZipException e) {
throw new RuntimeException("解压加密文件失败",e.getCause());
}
long endTime = System.currentTimeMillis(); //获取结束时间
log.warn("解压密码文件花费时间:" + (endTime - startTime) + "ms");
}
/**
* Description:删除指定文件夹下所有文件
*
* @param path 文件路径
* @return boolean
* @Author: wtl
* @Date: 2019/1/11 15:24
*/
public static boolean deleteDir(String path) {
File file = new File(path);
if (!file.exists()) {//判断是否待删除目录是否存在
return false;
}
//取得当前目录下所有文件和文件夹
String[] content = file.list();
for (String name : content) {
File temp = new File(path, name);
if (temp.isDirectory()) {//判断是否是目录
deleteDir(temp.getAbsolutePath());//递归调用,删除目录里的内容
temp.delete();//删除空目录
} else {
if (!temp.delete()) {//直接删除文件
log.warn("文件删除失败,文件名:" + name);
}
}
}
return true;
}
// 无加密压缩解压文件 begin
/**
* Description:压缩文件或文件夹
*
* @param srcFilePath 压缩源路径
* @param destFilePath 压缩目的路径
* @return void
* @Author: wtl
* @Date: 2019/1/9 10:17
*/
public static void compress(String srcFilePath, String destFilePath) {
long startTime = System.currentTimeMillis(); //获取开始时间
File src = new File(srcFilePath);
if (!src.exists()) {
throw new RuntimeException(srcFilePath + "不存在");
}
File zipFile = new File(destFilePath);
try {
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
String baseDir = "";
compressbyType(src, zos, baseDir);
zos.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
long endTime = System.currentTimeMillis(); //获取结束时间
log.warn("压缩花费时间:" + (endTime - startTime) + "ms");
}
/**
* Description:按照原路径的类型就行压缩。文件路径直接把文件压缩,
*
* @param file 压缩源文件
* @param outputStream 压缩目标文件
* @param baseDir
* @return void
* @Author: wtl
* @Date: 2019/1/9 10:17
*/
private static void compressbyType(File file, ZipOutputStream outputStream, String baseDir) {
if (!file.exists())
return;
/*System.out.println("压缩路径" + baseDir + file.getName());*/
//判断文件是否是文件,如果是文件调用compressFile方法,如果是路径,则调用compressDir方法;
if (file.isFile()) {
//src是文件,调用此方法
compressFile(file, outputStream, baseDir);
} else if (file.isDirectory()) {
//src是文件夹,调用此方法
compressDir(file, outputStream, baseDir);
}
}
/**
* Description:压缩文件
*
* @param file 压缩源文件
* @param outputStream 压缩目标文件
* @param baseDir
* @return void
* @Author: wtl
* @Date: 2019/1/9 10:17
*/
private static void compressFile(File file, ZipOutputStream outputStream, String baseDir) {
if (!file.exists())
return;
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
ZipEntry entry = new ZipEntry(baseDir + file.getName());
outputStream.putNextEntry(entry);
int count;
byte[] buf = new byte[1024];
while ((count = bis.read(buf)) != -1) {
outputStream.write(buf, 0, count);
}
bis.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Description:压缩文件夹
*
* @param dir 压缩源文件
* @param outputStream 压缩目标文件
* @param baseDir
* @return void
* @Author: wtl
* @Date: 2019/1/9 10:17
*/
private static void compressDir(File dir, ZipOutputStream outputStream, String baseDir) {
if (!dir.exists())
return;
File[] files = dir.listFiles();
if (files.length == 0) {
try {
outputStream.putNextEntry(new ZipEntry(baseDir + dir.getName() + File.separator));
} catch (IOException e) {
e.printStackTrace();
}
}
for (File file : files) {
compressbyType(file, outputStream, baseDir + dir.getName() + File.separator);
}
}
/**
* Description:解压文件
*
* @param srcFilePath 待解压的zip文件路径
* @param destDir 指定目录(以"\\"结尾)
* @return void
* @Author: wtl
* @Date: 2019/1/9 18:28
*/
public static void decompress(String srcFilePath, String destDir) throws IOException {
long startTime = System.currentTimeMillis(); //获取开始时间
File zipFile = new File(srcFilePath);
//解决中文文件夹乱码
ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String zipEntryName = entry.getName();
InputStream in = zip.getInputStream(entry);
String outPath = (destDir + zipEntryName).replaceAll("\\*", "/");
// 判断路径是否存在,不存在则创建文件路径
File file = new File(outPath.substring(0, outPath.lastIndexOf('\\')));
if (!file.exists()) {
file.mkdirs();
}
// 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
if (new File(outPath).isDirectory()) {
continue;
}
FileOutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[1024];
int len;
while ((len = in.read(buf1)) > 0) {
out.write(buf1, 0, len);
}
in.close();
out.close();
}
long endTime = System.currentTimeMillis(); //获取结束时间
log.warn("解压完毕,花费时间:" + (endTime - startTime) + "ms");
}
// 无加密压缩解压文件 end
}