这里写一个小例子,以下代码中有写main方法测试,实测是可以打包成功的!
package com.ways;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* Author: zh
* Desc: 压缩包工具类
*
*/
public class ZipUtil {
/**
* 把文件集合打成zip压缩包
* @param srcFiles 压缩文件集合
* @param zipFile zip文件名
* @throws RuntimeException 异常
*/
public static void toZip(List<File> srcFiles, File zipFile) throws RuntimeException {
// long start = System.currentTimeMillis();
if(zipFile == null){
System.out.println("压缩包文件名为空!");
return;
}
if(!zipFile.getName().endsWith(".zip")){
return;
}
ZipOutputStream zos = null;
FileOutputStream out = null;
try {
out = new FileOutputStream(zipFile);
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
byte[] buf = new byte[1024*1024*10];
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
zos.setComment("我是注释");
in.close();
}
zos.closeEntry();
// long end = System.currentTimeMillis();
} catch (Exception e) {
throw new RuntimeException("zipFile error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) { //""
//先把EXCEL写到临时目录,用来获取文件大小,最后删除
File f = new File("/home/zhaohy/myspace/workspace/mavenTest/WebContent/file/test1.xls");
File f1 = new File("/home/zhaohy/myspace/workspace/mavenTest/WebContent/file/test2.xls");
List<File> srcFiles = new ArrayList<File>();
srcFiles.add(f);
srcFiles.add(f1);
File zipFile = new File("/home/zhaohy/myspace/workspace/mavenTest/WebContent/file/newZip.zip");
if(!zipFile.exists()) {
try {
zipFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ZipUtil.toZip(srcFiles, zipFile);
}
}
如图test1.xls和test2.xls已经被打包进newZip.zip文件里
深度截图_选择区域_20190909220113.png
网友评论