Apache common提供了很多实用的工具包,下面就说一下如何用compress包来压缩文件夹。先引入compress,io和lang3这3个工具包:
<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包,并输出到文件流中,可以直接写入到文件或提供给前端下载,工具类如下:文章来源:https://www.toymoban.com/news/detail-809349.html
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包。文章来源地址https://www.toymoban.com/news/detail-809349.html
到了这里,关于Java利用Apache compress包实现文件夹压缩成Zip包的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!