Apache common提供了很多实用的工具包,下面就说一下如何用compress包来压缩文件夹。先引入compress,io和lang3这3个工具包:
java
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8</version>
</dependency>
</dependencies>
这个方法实现了将文件夹下所有的文件压缩成zip包,并输出到文件流中,可以直接写入到文件或提供给前端下载,工具类如下:
java
import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
public class ZipUtils {
/**
* 压缩文件夹下的所有文件
* @param dir 要压缩的文件夹
* @param outputStream 输出压缩后的文件流
* @throws IOException IO异常
* @throws ArchiveException 压缩异常
*/
public static void zip(File dir, OutputStream outputStream) throws IOException, ArchiveException {
ZipArchiveOutputStream zipOutput = null;
try {
zipOutput = (ZipArchiveOutputStream) new ArchiveStreamFactory()
.createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputStream);
zipOutput.setEncoding("utf-8");
zipOutput.setUseZip64(Zip64Mode.AsNeeded);
Collection<File> files = FileUtils.listFilesAndDirs(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
for (File file : files) {
InputStream in = null;
try {
if (file.getPath().equals(dir.getPath())) {
continue;
}
String relativePath = StringUtils.replace(file.getPath(), dir.getPath() + File.separator, "");
ZipArchiveEntry entry = new ZipArchiveEntry(file, relativePath);
zipOutput.putArchiveEntry(entry);
if (file.isDirectory()) {
zipOutput.closeArchiveEntry();
continue;
}
in = new FileInputStream(file);
IOUtils.copy(in, zipOutput);
zipOutput.closeArchiveEntry();
} finally {
if (in != null) {
IOUtils.closeQuietly(in);
}
}
}
zipOutput.finish();
} finally {
IOUtils.closeQuietly(zipOutput);
}
}
public static void main(String args[]) throws IOException, ArchiveException {
//要压缩的文件路径
File dir = new File("C:\\data\\data");
//压缩后zip包文件路径
File dest = new File("C:\\data\\test.zip");
OutputStream outputStream = new FileOutputStream(dest);
zip(dir, outputStream);
}
}
执行main函数跑测试用例,发现程序将dir路径下的所有文件已经压缩并输出zip包。