压缩工具类代码
package com.toycloud.awaken.platform.util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 压缩工具类
* 2020-02-11
* cfyang
*/
@Component
public class ZipCompress {
private String zipFileName = "out.zip"; // 目的地Zip文件
private static String outZip ; // 目的地Zip文件
private static String outTxt; // 源文件(带压缩的文件或文件夹)
@Value("${ocr.outTxt}")
public void setOutTxt(String outTxt) {
this.outTxt = outTxt;
}
@Value("${ocr.outZip}")
public void setOutZip(String outZip) {
this.outZip = outZip;
}
public boolean zip() {
//File zipFile = new File(zipFileName);
File txtFile = new File(outTxt);
if(!txtFile.exists()){ // 不存在txt文件
return false;
}
System.out.println("开始压缩中...");
long begin = System.currentTimeMillis();
//创建zip输出流
File zipFile = new File(outZip+"/"+zipFileName);
if (zipFile.exists()) { // 存在out.zip 先删除
zipFile.delete();
}
try {
new File(outZip).mkdirs();
zipFile.createNewFile();
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outZip+"/"+zipFileName));
//创建缓冲输出流
BufferedOutputStream bos = new BufferedOutputStream(out);
File sourceFile = new File(outTxt);
//调用函数
boolean res = compress(out, bos, sourceFile, sourceFile.getName());
bos.close();
out.close();
if(!res){
System.out.println("便利文件夹压缩失败,ZipCompress.compress()中错误,ZipCompress.zip()调用错误");
return false;
}
long currentTimeMillis = System.currentTimeMillis();
System.out.println(outZip+"/"+zipFileName + "压缩完成(100%)....." + (currentTimeMillis - begin) + "ms");
} catch (IOException e) {
e.printStackTrace();
System.out.println(e.getMessage());
return false;
}
return true;
}
public boolean compress(ZipOutputStream out, BufferedOutputStream bos, File sourceFile, String base) {
//如果路径为目录(文件夹)
if (sourceFile.isDirectory()) {
//取出文件夹中的文件(或子文件夹)
File[] flist = sourceFile.listFiles();
if (flist.length == 0) {//如果文件夹为空,则只需在目的地zip文件中写入一个目录进入点
//System.out.println("空:******"+base+"/");
try {
out.putNextEntry(new ZipEntry(base + File.separator));
} catch (IOException e) {
e.printStackTrace();
System.out.println(e.getMessage());
return false;
}
} else {//如果文件夹不为空,则递归调用compress,文件夹中的每一个文件(或文件夹)进行压缩
for (int i = 0; i < flist.length; i++) {
compress(out, bos, flist[i], base + "/" + flist[i].getName());
}
}
} else {//如果不是目录(文件夹),即为文件,则先写入目录进入点,之后将文件写入zip文件中
try {
out.putNextEntry(new ZipEntry(base));
FileInputStream fos = new FileInputStream(sourceFile);
BufferedInputStream bis = new BufferedInputStream(fos);
int tag;
// System.out.println(base);
//将源文件写入到zip文件中
while ((tag = bis.read()) != -1) {
bos.write(tag);
}
bos.flush();
bis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println(e.getMessage());
return false;
}
}
return true;
}
}
调用:
ZipCompress compress = new ZipCompress();
try {
boolean bl = compress.zip(); // 压缩文件
if(bl){ // 压缩成功,下载文件
}else{// 失败
}
} catch (Exception e) {
e.printStackTrace();
}