package com.jcjt.download.utils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import java.io.*;
/**
* 压缩文件操作类 <br>
*/
public class ZipUtils {
private static final int BUFFER_SIZE = 2 * 1024;
public static void toZip(String srcDir, OutputStream out) throws RuntimeException{
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
File sourceFile = new File(srcDir);
compress(sourceFile,zos,sourceFile.getName());
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if(zos != null){
zos.flush();
zos.close();
}
}catch (Exception e){
throw new RuntimeException("ZIP流关闭失败");
}
}
}
private static void compress(File sourceFile, ZipOutputStream zos, String name) throws Exception{
byte[] buf = new byte[BUFFER_SIZE];
if(sourceFile.isFile()){
// 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
//一定要设置GBK否则下载后zip内部文件中文乱码
zos.setEncoding("GBK");
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);
}
zos.closeEntry();
in.close();
}else{
File[] listFiles = sourceFile.listFiles();
for (File file : listFiles){
compress(file, zos, name + "/" + file.getName());
}
}
}
//删除源文件
public static void deleteSourceFile(File sourceFile){
if(sourceFile.exists()){
if(sourceFile.isFile()){
sourceFile.delete();
}else {
File[] files = sourceFile.listFiles();
for(File file : files){
deleteSourceFile(file);
}
sourceFile.delete();
}
}else {
System.out.println("文件不存在!");
}
}
}