效果图
- 压缩前
- 压缩后
代码
public class ZipMultiFile {
public static void main(String[] args) {
File[] srcFiles = { new File("F:\\tmp\\a.png"), new File("F:\\tmp\\b.txt"), new File("F:\\tmp\\c.docx") };
File zipFile = new File("F:\\tmp\\ZipFile"+System.currentTimeMillis()+".zip");
zipFiles(srcFiles, zipFile);
}
public static void zipFiles(File[] srcFiles, File zipFile) {
if (!zipFile.exists()) {
try {
zipFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileOutputStream fileOutputStream = null;
ZipOutputStream zipOutputStream = null;
FileInputStream fileInputStream = null;
try {
fileOutputStream = new FileOutputStream(zipFile);
zipOutputStream = new ZipOutputStream(fileOutputStream);
ZipEntry zipEntry = null;
for (int i = 0; i < srcFiles.length; i++) {
fileInputStream = new FileInputStream(srcFiles[i]);
zipEntry = new ZipEntry(srcFiles[i].getName());
zipOutputStream.putNextEntry(zipEntry);
int len;
byte[] buffer = new byte[1024];
while ((len = fileInputStream.read(buffer)) > 0) {
zipOutputStream.write(buffer, 0, len);
}
}
zipOutputStream.closeEntry();
zipOutputStream.close();
fileInputStream.close();
fileOutputStream.close();
System.out.println("压缩成功");
} catch (IOException e) {
e.printStackTrace();
}
}
}
原文链接:https://www.cnblogs.com/jpfss/p/9830594.html