本地文件打包以zip形式导出
一、如何将本地服务器上的文件打包成zip?
项目中,需要将多个excel打包导出到前端,以下可以编写为一个工具类,调用即可;
- 获取本地文件,最好将要打包的放在一个文件夹下,避免多次递归调用
- 递归打包进入一个zip
- 将该zip响应给用户
二、主要代码
1.编写压缩方法
/**
* 压缩
* @param sourceFileName 源文件全路径
* @param response 响应流
*/
public void zip(String sourceFileName, HttpServletResponse response){
ZipOutputStream out = null;
BufferedOutputStream bos = null;
// 这里的源文件目录换成你自己的就好,也可以写在配置文件里面,传进来
sourceFileName="D:/test";
try {
//将zip以流的形式输出到前台
response.setHeader("content-type", "application/octet-stream");
response.setCharacterEncoding("utf-8");
// 设置浏览器响应头对应的Content-disposition
// 参数中 export 为压缩包文件名,尾部的.zip 为文件后缀
// 若传递中文文件名,需要转换,将文件名改成自己的即可
//new String ("文件名".getBytes("GBK"),"ISO-8859-1");
response.setHeader("Content-disposition",
"attachment;filename=" + new String("export"+".zip"));
//创建zip输出流
out = new ZipOutputStream(response.getOutputStream());
File sourceFile = new File(sourceFileName);
//调用压缩函数
compress(out, bos, sourceFile, sourceFile.getName());
//关流
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
2.compress递归压缩方法
/**
* 文件压缩
* 判断传入sourceFile是否为文件或者文件夹
* 若为文件夹则判断是否有文件
* 若不包含文件则直接打包这个文件夹
* 若包含文件,则递归调用此方法
* 若为文件,获取文件的输入流,写入zip中
* @param out zip文件的输出流
* @param sourceFile 源文件
* @param base 写入路径
*/
public void compress(ZipOutputStream out, File sourceFile, String base){
FileInputStream fos = null;
BufferedInputStream bis = null;
try {
//如果路径为目录(文件夹)
if (sourceFile.isDirectory()) {
//取出文件夹中的文件(或子文件夹)
File[] flist = sourceFile.listFiles();
if (flist.length == 0) {
//如果文件夹为空,则只需在目的地zip文件中写入一个目录进入点
out.putNextEntry(new ZipEntry(base + "/"));
} else {
//如果文件夹不为空,则递归调用compress,获取文件夹中的每一个文件(或文件夹)进行压缩
for (int i = 0; i < flist.length; i++) {
// 传递当前zip路径拼上写入的文件名
compress(out, flist[i], base + "/" + flist[i].getName());
}
}
} else {
//如果不是目录(文件夹),即为文件,则先写入目录进入点,之后将文件写入zip文件中
out.putNextEntry(new ZipEntry(base));
fos = new FileInputStream(sourceFile);
bis = new BufferedInputStream(fos);
int tag;
//将源文件写入到zip文件中
while ((tag = bis.read()) != -1) {
out.write(tag);
}
bis.close();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
总结
本文仅仅展示了本地文件打包zip的过程,对于从数据库中导出excel,或者将多个excel直接打包,请看另外一篇,有用点个赞哦