package com.ruoyi.common.utils;
|
|
import com.ruoyi.common.config.RuoYiConfig;
|
import org.apache.commons.io.IOUtils;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
|
import java.io.*;
|
import java.util.List;
|
import java.util.zip.ZipEntry;
|
import java.util.zip.ZipOutputStream;
|
|
public class ZipUtils {
|
private static final Logger log = LoggerFactory.getLogger(ZipUtils.class);
|
|
/**
|
* 获取下载路径
|
*
|
* @param filename 文件名称
|
*/
|
public static String getAbsoluteFile(String filename)
|
{
|
String downloadPath = RuoYiConfig.getDownloadPath() + filename;
|
File desc = new File(downloadPath);
|
if (!desc.getParentFile().exists())
|
{
|
desc.getParentFile().mkdirs();
|
}
|
return downloadPath;
|
}
|
/**
|
* 压缩多个文件
|
*/
|
public static void generatorZipFile(String fileName,List<String> fileSrcs,boolean delFileSrc)
|
{
|
FileOutputStream outputStream = null;
|
ZipOutputStream zip=null;
|
try {
|
outputStream = new FileOutputStream(new File(getAbsoluteFile(fileName)));
|
zip = new ZipOutputStream(outputStream);
|
int i =0;
|
for (String src : fileSrcs)
|
{
|
i++;
|
FileInputStream in = null;
|
String fItemName=null;
|
File f=null;
|
try {
|
f= new File(getAbsoluteFile(src));
|
fItemName= f.getName();
|
in = new FileInputStream(f);
|
byte[] buffer = new byte[in.available()];
|
in.read(buffer);
|
// 添加到zip
|
zip.putNextEntry(new ZipEntry(fItemName.replace(".",i+".")));
|
IOUtils.write(buffer, zip);
|
zip.flush();
|
zip.closeEntry();
|
}
|
catch (IOException e){log.error("压缩文件{}失败",fItemName, e);}finally {
|
IOUtils.closeQuietly(in);
|
}
|
if(delFileSrc){
|
if(f!=null){try {f.delete();}finally {} }
|
}
|
}
|
} catch (FileNotFoundException e) {
|
log.error("异常",e);
|
}finally {
|
try{if(zip!=null){IOUtils.closeQuietly(zip);}}finally { }
|
try{if(outputStream!=null){IOUtils.closeQuietly(outputStream);}}finally { }
|
}
|
}
|
|
}
|