- 原生ZipOutputStream
public void zip(File fileToZip, String relativePath, ZipOutputStream zipOut) throws IOException {
if (fileToZip.isHidden()) {
return;
}
if (fileToZip.isDirectory()) {
if (relativePath.endsWith("/")) {
zipOut.putNextEntry(new ZipEntry(relativePath));
zipOut.closeEntry();
} else {
zipOut.putNextEntry(new ZipEntry(relativePath + "/"));
zipOut.closeEntry();
}
File[] children = fileToZip.listFiles();
if (children != null) {
for (File childFile : children) {
zip(childFile, relativePath + "/" + childFile.getName(), zipOut);
}
}
return;
}
FileInputStream fis = new FileInputStream(fileToZip);
ZipEntry zipEntry = new ZipEntry(relativePath);
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
}
- commons-compress
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.20</version>
</dependency>
private void zip(File source, File destination) throws IOException, ArchiveException {
OutputStream archiveStream = new FileOutputStream(destination);
ArchiveOutputStream archive = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP, archiveStream);
Collection<File> fileList = FileUtils.listFiles(source, null, true);
for (File file : fileList) {
String entryName = getEntryName(source, file);
ZipArchiveEntry entry = new ZipArchiveEntry(entryName);
archive.putArchiveEntry(entry);
BufferedInputStream input = new BufferedInputStream(new FileInputStream(file));
IOUtils.copy(input, archive);
input.close();
archive.closeArchiveEntry();
}
archive.finish();
archiveStream.close();
}
private String getEntryName(File source, File file) throws IOException {
int index = source.getAbsolutePath().length() + 1;
String path = file.getCanonicalPath();
return path.substring(index);
}
- zip4j
使用maven:<!-- https://mvnrepository.com/artifact/net.lingala.zip4j/zip4j -->
<dependency>
<groupId>net.lingala.zip4j</groupId>
<artifactId>zip4j</artifactId>
<version>2.6.1</version>
</dependency>
代码:
<!-- 压缩文件,并下载 -->
public void zip(File fileToZip, File zip, HttpServletResponse response) throws ZipException {
ZipFile zipFile = new ZipFile(zip);
ZipParameters parameters = new ZipParameters();
// 压缩方式
parameters.setCompressionMethod(CompressionMethod.DEFLATE);
// 压缩级别
parameters.setCompressionLevel(CompressionLevel.FAST);
// 要打包的文件夹
File[] fs = fileToZip.listFiles();
// 遍历test文件夹下所有的文件、文件夹
for (File f : fs) {
if (f.isDirectory()) {
zipFile.addFolder(f, parameters);
} else {
zipFile.addFile(f, parameters);
}
}
OutputStream outputStream = response.getOutputStream();
InputStream fis = new FileInputStream(zipFile.getFile());
// 将压缩文件写入到输出流
IOUtils.copy(fis, outputStream);
}