java使用apache compress高效的压缩文件夹代码
时间: 2023-10-14 08:06:17 浏览: 212
java压缩文件代码
下面是使用Apache Commons Compress库进行高效压缩文件夹的Java代码示例:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.utils.IOUtils;
public class FolderCompressionExample {
public static void main(String[] args) {
String sourceFolderPath = "path/to/source/folder";
String destinationZipFilePath = "path/to/destination/archive.zip";
compressFolder(sourceFolderPath, destinationZipFilePath);
}
private static void compressFolder(String sourceFolderPath, String destinationZipFilePath) {
try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(new FileOutputStream(destinationZipFilePath))) {
File sourceFolder = new File(sourceFolderPath);
compressFilesRecursively(zipOut, sourceFolder, "");
zipOut.finish();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void compressFilesRecursively(ZipArchiveOutputStream zipOut, File sourceFile, String parentPath) throws IOException {
String entryName = parentPath + sourceFile.getName();
ArchiveEntry entry = zipOut.createArchiveEntry(sourceFile, entryName);
zipOut.putArchiveEntry(entry);
if (sourceFile.isFile()) {
try (FileInputStream fis = new FileInputStream(sourceFile)) {
IOUtils.copy(fis, zipOut);
}
zipOut.closeArchiveEntry();
} else if (sourceFile.isDirectory()) {
zipOut.closeArchiveEntry();
File[] children = sourceFile.listFiles();
if (children != null) {
for (File child : children) {
compressFilesRecursively(zipOut, child, entryName + "/");
}
}
}
}
}
```
上述代码使用Apache Commons Compress库创建了一个Zip压缩文件,并递归地将指定文件夹下的所有文件和子文件夹压缩到该Zip文件中。你只需要将`sourceFolderPath`和`destinationZipFilePath`替换为实际的文件夹路径和目标压缩文件路径。
阅读全文