作者:liaojiawei | 来源:互联网 | 2023-10-10 10:40
/**
* 压缩成ZIP 方法 * @param srcFiles 需要压缩的文件列表
* @param out 压缩文件输出流
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static void toZip(List srcFiles , OutputStream out){
long start = System.currentTimeMillis();
try (ZipOutputStream zos = new ZipOutputStream(out);) {
for (File srcFile : srcFiles) {byte[] buf = new byte[BUFFER_SIZE];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.closeEntry();in.close();
}
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) +" ms");
} catch (Exception e) {
e.printStackTrace();
}
}
调用方式
public class ClacTest {
public static void main(String[] args) throws FileNotFoundException {
ZipFileUtil zf = new ZipFileUtil();
List files = new ArrayList();
//确保下面文件存在
files.add(new File("E:/res/"+1096251018+"_Bpic.xml"));
files.add(new File("e:/picture/"+"1096251018-3_"+"o.jpg"));
files.add(new File("e:/picture/"+"1096251018-1_"+"o.jpg"));
files.add(new File("e:/picture/"+"1096251018-2_"+"o.jpg"));
zf.toZip(files,new FileOutputStream(new File("E:/picture.zip")));
}
}
可以