import java.io.File; import java.io.IOException; import java.io.FileOutputStream; import java.io.InputStream; import java.io.BufferedOutputStream; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream;
/** * 将多个文件压缩成zip文件 * * @param fileList 文件列表 * @param zipName 压缩后的文件名 * @throws IOException */ public void toZipFile(List<File> fileList, String zipName) throws IOException { String tmpPath = System.getProperty("java.io.tmpdir"); String tmpZipName = tmpPath + File.separator + zipName; System.out.println(tmpPath); FileOutputStream fileOutputStream = null; ZipOutputStream zipOutputStream = null; InputStream inputStream = null; BufferedOutputStream bufferedOutputStream = null; BufferedInputStream bufferedInputStream = null; try { fileOutputStream = new FileOutputStream(tmpZipName); bufferedOutputStream = new BufferedOutputStream(fileOutputStream); zipOutputStream = new ZipOutputStream(bufferedOutputStream); for (int index = 0; index < fileList.size(); index++) { inputStream = new FileInputStream(fileList.get(index)); bufferedInputStream = new BufferedInputStream(inputStream); ZipEntry zipEntry = new ZipEntry(fileList.get(index).getName()); zipOutputStream.putNextEntry(zipEntry); int len; byte[] buffer = new byte[1024]; while ((len = bufferedInputStream.read(buffer)) > 0) { zipOutputStream.write(buffer, 0, len); } } } finally { if (zipOutputStream != null) { zipOutputStream.closeEntry(); zipOutputStream.close(); } if (bufferedOutputStream != null) { bufferedOutputStream.flush(); bufferedOutputStream.close(); } if (bufferedInputStream != null) { bufferedInputStream.close(); } if (inputStream != null) { inputStream.close(); } if (fileOutputStream != null) { fileOutputStream.close(); } } }
喜欢的小伙伴可以点赞收藏加关注,希望这篇文章能够帮助到大家哟!