java将多个文件添加到压缩文件中并在浏览器导出
解决方法:
1.核心方法
public static void toZip(List<File> srcFiles , OutputStream out)throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null ;
try {
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
byte[] buf = new byte[1024];
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();
} catch (Exception e) {
throw new RuntimeException("压缩失败!",e);
}finally{
if(zos != null){
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.使用方法
List<File> srcFiles =new ArrayList<File>();
FileOutputStream fos = new FileOutputStream(new File("F:/test.wav"));
toZip(srcFiles, fos);
本文链接:http://www.yayihouse.com/yayishuwu/chapter/1756