import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream;
/** * 将多个文件压缩成zip文件 * * @param fileList 文件列表 * @param zipName 压缩后的文件名 * @throws IOException */ public void toZipFile(ListfileList, String zipName) throws IOException { String tmpPath = System.getProperty("java.io.tmpdir"); System.out.println(tmpPath); String tmpZipName = tmpPath + File.separator + zipName; FileOutputStream fileOutputStream = null; ZipOutputStream zipOutputStream = null; FileInputStream fileInputStream = null; try { fileOutputStream = new FileOutputStream(tmpZipName); zipOutputStream = new ZipOutputStream(fileOutputStream); for (int index = 0; index < fileList.size(); index++) { fileInputStream = new FileInputStream(fileList.get(index)); ZipEntry zipEntry = new ZipEntry(fileList.get(index).getName()); zipOutputStream.putNextEntry(zipEntry); int len; byte[] buffer = new byte[1024]; while ((len = fileInputStream.read(buffer)) > 0) { zipOutputStream.write(buffer, 0, len); } } } finally { if (zipOutputStream != null) { zipOutputStream.closeEntry(); zipOutputStream.close(); } if (fileInputStream != null) { fileInputStream.close(); } if (fileOutputStream != null) { fileOutputStream.close(); } } }
需要java资料请用微信扫二维码
