注意:開關流的循序:類似棧的輸入輸出
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.springframework.util.StreamUtils.BUFFER_SIZE;
/**
* Author: zh
* Desc: 壓縮包工具類
* Date: Created in 2018/5/19 13:51
*/
public class FileToZip {
/**
* 把文件集合打成zip壓縮包
* @param srcFiles 壓縮文件集合
* @param zipFile zip文件名
* @throws RuntimeException 異常
*/
public static void toZip(List<File> srcFiles, File zipFile) throws RuntimeException {
if(zipFile == null){
return;
}
if(!zipFile.getName().endsWith(".zip")){
return;
}
ZipOutputStream zos = null;
try {
FileOutputStream out = new FileOutputStream(zipFile);
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
byte[] buf = new byte[BUFFER_SIZE];
zos.putNextEntry(new ZipEntry(srcFile.getName()));
System.out.println( "srcFile.getName()"+srcFile.getName());
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
in.close();
zos.closeEntry();
}
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
System.out.println("ZipUtil toZip close exception" + e);
}
}
out.close();
} catch (Exception e) {
throw new RuntimeException("zipFile error from ZipUtils", e);
}
}
}