这个方法可以将指定文件夹中的文件压缩成zip包,参考了别人的文章修改成的(参考文章找不到了,这是我完成功能后有空整理的代码,如果侵权请联系我删除),并加上了删除指定路径下的文件,可以保证在服务器上存放临时文件的文件夹为空,这样直接压缩该文件夹的所有文件就可以了
package cc.mrbird.febs.server.system.utils;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 将文件中所有文件及文件夹压缩
* source: 文件源的路径
* dest: 压缩文件存放路径
*/
@Component
public class ZipFileUtil {
//获取文件源中的所有文件
private List<File> getSourceAllFiles(String from){
List<File> fileList=new ArrayList<>();
File fromfile=new File(from);
File[] fileArr=fromfile.listFiles();
for (File file : fileArr) {
if(file.isFile()){
fileList.add(file);
}else{
//利用递归之法,获取路径中子路径中的所有文件
fileList.addAll(getSourceAllFiles(file.getPath()));
}
}
return fileList;
}
//得到文件在文件夹中的相对路径 保持原有结构 (也可以根据需求自己创建新的结构)
private String getRelName(String from,File f){
String name=null;
name=f.getAbsolutePath().replace(from+"\\", "");
name=name.replace("\\", "/");
System.out.println("文件相对路径是:"+name);
return name;
}
//创建一个压缩文件,并存放到新的路径中
public void createZipFile(String from, String dest){
List<File> fileList=getSourceAllFiles(from);
ZipOutputStream zout=null; //生成Zip输出流
try {
zout=new ZipOutputStream(new FileOutputStream(new File(dest)));
//将每个文件放入Zip流中
for (File f : fileList) {
InputStream is=new FileInputStream(f);
String name=getRelName(from, f); //获取文件相对路径 保持文件原有结构
ZipEntry en=new ZipEntry(new File(from).getName()+"/"+name); // ZipEntry ens=new ZipEntry(f.getName()); //这样只是把单独的文件压缩,不再有之前的结构
en.setSize(f.length());
zout.putNextEntry(en);
zout.setComment("test");
//读取文件中的内容
int len=0;
byte[] buffer=new byte[1024];
while((len=is.read(buffer))!=-1){
zout.write(buffer,0,len);
}
zout.flush();
is.close();
}
zout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(zout!=null){
try {
zout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 删除指定文件夹下的所有文件
* @param path
* @return
*/
public static boolean delAllFile(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
}
return flag;
}
public static void main(String[] args) {
ZipFileUtil test=new ZipFileUtil();
test.createZipFile("D:\\EDI_MULIT_DOWNLOAD\\5fd0998a07c84d9d924076f64fb726a7", "D:\\sumZip\\co.zip");
}
}