import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @Author windwardbird
* @packageName
* @time 2020/9/17 9:56
* @describeOfFunction: 生成zip
*/
@Slf4j
public class GenerateZipUtils {
private static final String TARGET_PATH = "D:"+File.separator+"test"+File.separator+""; //生成zip的路径
private static fianl String MARK_OK = "生成zip成功";
private static fianl String MARK_FAIL = "生成zip失败";
/**
* @description:
* @date: 2020/9/17 9:59
* @param: sourcePath 原文件路径 zipName 生成zip 压缩包名字
* @return:
*/
public String createZip(String sourcePath, String zipName) throws Exception{
String zipPath = TARGET_PATH;
File sourceFile = new File(sourcePath);
FileInputStream fis = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
ZipOutputStream zos = null;
if(!sourceFile.exists()){
log.error(sourcePath + "not exist!");
}else{
if (!new File(zipPath).exists()) {
new File(zipPath).mkdirs(); //不存在创建文件夹多层目录
}
File zipFile = new File(zipPath + File.separator + zipName + ".zip");
if(zipFile.exists()){
log.info(zipPath + zipName + ".zip" + "is exist");
}else{
File[] sourceFiles = sourceFile.listFiles();
if(null==sourceFiles ||sourceFile.length()<1){
log.info("not found file");
}else{
try {
// 原文件夹下有文件,进行压缩
fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(new BufferedOutputStream(fos));
byte[] bufs = new byte[1024 * 64];
for (int i = 0; i < sourceFiles.length; i++) {
ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
if(sourceFiles[i].getName().endsWith(".zip")||sourceFiles[i].getName().endsWith(".rar")) continue;
zos.putNextEntry(zipEntry);
fis = new FileInputStream(sourceFiles[i]);
bis = new BufferedInputStream(fis, 1024 * 64);
int read = 0;
while ((read = bis.read(bufs, 0, 1024 * 64)) != -1) {
zos.write(bufs, 0, read);
}
}
result = MARK_OK ;
} catch (IOException e) {
e.printStackTrace();
log.error(e.getMessage());
} finally {
// 关流
try {
if (null != bis) bis.close();
if (null != zos) zos.close();
} catch (IOException e) {
e.printStackTrace();
log.error(e.getMessage());
}
}
}
}
}
return MARK_FAIL ;
}
}
生成zip压缩包
最新推荐文章于 2021-03-09 20:08:50 发布

1648





