package sol.edrms.v2.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @Author:
* @Time:
* @Description:
*/
@Slf4j
public class FileUtil {
private static final int BUFFER_SIZE = 2 * 1024;
/**
* 压缩文件夹
*
* @param sourceFile 要压缩的文件夹
* @param out
* @param KeepDirStructure true
* @throws RuntimeException
*/
public static void toZip(File sourceFile, OutputStream out, boolean KeepDirStructure) throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
compress(sourceFile, zos, "", KeepDirStructure);
long end = System.currentTimeMillis();
log.info("压缩完成,耗时:{}ms", end - start);
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 删除压缩之前的文件夹
if (sourceFile != null) {
log.info("正在删除原文件~");
deleteFile(sourceFile);
}
}
}
斜体样式private static void compress(File sourceFile, ZipOutputStream zos, String name,
boolean KeepDirStructure) throws Exception {
byte[] buf = new byte[BUFFER_SIZE];
if (sourceFile.isFile()) {
// 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
zos.putNextEntry(new ZipEntry(name));
// copy文件到zip输出流中
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
// Complete the entry
zos.closeEntry();
in.close();
} else {
File[] listFiles = sourceFile.listFiles();
if (listFiles == null || listFiles.length == 0) {
// 需要保留原来的文件结构时,需要对空文件夹进行处理
if (KeepDirStructure) {
// 空文件夹的处理
if (!StringUtils.isEmpty(name)) {
zos.putNextEntry(new ZipEntry(name + "/"));
} else {
zos.putNextEntry(new ZipEntry(""));
}
// 没有文件,不需要文件的copy
zos.closeEntry();
}
} else {
for (File file : listFiles) {
// 判断是否需要保留原来的文件结构
if (KeepDirStructure) {
// 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
// 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
if (!StringUtils.isEmpty(name)) {
compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
} else {
compress(file, zos, "" + file.getName(), KeepDirStructure);
}
} else {
compress(file, zos, file.getName(), KeepDirStructure);
}
}
}
}
}
/**
* 设置导出zip的响应格式
*
* @param request
* @param response
* @param fileZip zip的名字
* @param filePath zip的路径
* @throws UnsupportedEncodingException
*/
public static void downLoadFile(HttpServletRequest request, HttpServletResponse response, String fileZip, String filePath) throws UnsupportedEncodingException {
//进行浏览器下载
final String userAgent = request.getHeader("USER-AGENT");
//判断浏览器代理并分别设置响应给浏览器的编码格式
String finalFileName = null;
if (StringUtils.contains(userAgent, "MSIE") || StringUtils.contains(userAgent, "Trident")) {
// IE浏览器
finalFileName = URLEncoder.encode(fileZip, "UTF8");
System.out.println("IE浏览器");
} else if (StringUtils.contains(userAgent, "Mozilla")) {
// google,火狐浏览器
finalFileName = new String(fileZip.getBytes(), "ISO8859-1");
} else {
// 其他浏览器
finalFileName = URLEncoder.encode(fileZip, "UTF8");
}
// 告知浏览器下载文件,而不是直接打开,浏览器默认为打开
response.setContentType("application/x-download");
// 下载文件的名称
response.setHeader("Content-Disposition", "attachment;filename=\"" + finalFileName + "\"");
ServletOutputStream servletOutputStream = null;
try {
servletOutputStream = response.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
DataOutputStream temps = new DataOutputStream(
servletOutputStream);
// 浏览器下载文件的路径
DataInputStream in = null;
try {
in = new DataInputStream(
new FileInputStream(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] b = new byte[2048];
// 之后用来删除临时压缩文件
File reportZip = new File(filePath);
try {
while ((in.read(b)) != -1) {
temps.write(b);
}
temps.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (temps != null) {
try {
temps.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (reportZip != null) {
// 删除服务器本地产生的临时压缩文件!
reportZip.delete();
}
try {
servletOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static Boolean deleteFile(File file) {
//判断文件不为null或文件目录存在
if (file == null || !file.exists()) {
log.info("文件删除失败,请检查文件是否存在以及文件路径是否正确");
return false;
}
//获取目录下子文件
File[] files = file.listFiles();
//遍历该目录下的文件对象
for (File f : files) {
//判断子目录是否存在子目录,如果是文件则删除
if (f.isDirectory()) {
//递归删除目录下的文件
deleteFile(f);
} else {
//文件删除
f.delete();
//打印文件名
log.info("文件名:" + f.getName());
}
}
//文件夹删除
file.delete();
log.info("目录名:" + file.getName());
return true;
}
}
java压缩文件夹并导出ZIP工具类
最新推荐文章于 2024-04-08 00:34:17 发布