1、引人
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;类
2、方法
/*
billNos:要打包的文件列表
suffix:后缀名
return 打包文件路径
*/
private String packZip(List<String> billNos, String suffix) throws Exception{
byte[] buffer = new byte[1024];
String dir = FileUtils.rootPath + "report/";//文件所在目录
File file;
String strZipName = "sample.zip";//名称
String path = dir + strZipName;//文件路径
File file1 = new File(path);
//判断打包文件是否存在,如果存在就删除
if(file1.exists()) {
file1.delete();
}
file1.createNewFile();//新建打包文件
String fileName;
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(path));
out.setEncoding("utf-8");//设置编码格式
FileInputStream fis;
int len;
for(String s:billNos){
fileName = dir + s+ suffix;//要打包的文件名称
file = new File(fileName);
fis = new FileInputStream(file);
out.putNextEntry(new ZipEntry(file.getName()));
while((len = fis.read(buffer))>0){
out.write(buffer,0,len);
}
out.closeEntry();
fis.close();
}
out.close();//关闭
return "report/" + strZipName;
}