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();
}
}
}
喜欢的小伙伴可以点赞收藏加关注,希望这篇文章能够帮助到大家哟!
该篇博客详细介绍了如何使用Java的IO和ZipOutputStream类将多个文件压缩成ZIP文件,包括创建临时文件、初始化输出流、添加ZipEntry以及关闭流等关键步骤。适合Java初学者和需要处理文件压缩的开发者参考。

被折叠的 条评论
为什么被折叠?



