Apache Commons Compress 如何实现文件压缩与解压
时间: 2023-12-10 09:38:09 浏览: 280
Apache Commons Compress 是一个用于处理压缩文件的开源 Java 库,它支持多种压缩格式,包括 ZIP、TAR、GZIP、BZIP2 等。
下面是使用 Apache Commons Compress 实现文件压缩与解压的示例代码:
## 压缩文件
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveOutputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
public class FileCompressor {
public static void compress(File source, File destination) throws Exception {
try (FileOutputStream fos = new FileOutputStream(destination);
GzipCompressorOutputStream gzos = new GzipCompressorOutputStream(fos);
TarArchiveOutputStream tos = new TarArchiveOutputStream(gzos)) {
ArchiveEntry entry = new TarArchiveEntry(source.getName());
entry.setSize(source.length());
tos.putArchiveEntry(entry);
FileInputStream fis = new FileInputStream(source);
byte[] buffer = new byte[4096];
int count;
while ((count = fis.read(buffer)) != -1) {
tos.write(buffer, 0, count);
}
fis.close();
tos.closeArchiveEntry();
}
}
}
```
## 解压文件
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
public class FileExtractor {
public static void extract(File source, File destination) throws Exception {
try (FileInputStream fis = new FileInputStream(source);
GzipCompressorInputStream gzis = new GzipCompressorInputStream(fis);
ArchiveInputStream ais = new TarArchiveInputStream(gzis)) {
ArchiveEntry entry;
while ((entry = ais.getNextEntry()) != null) {
if (!ais.canReadEntryData(entry)) {
continue;
}
File file = new File(destination, entry.getName());
if (entry.isDirectory()) {
file.mkdirs();
} else {
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[4096];
int count;
while ((count = ais.read(buffer)) != -1) {
fos.write(buffer, 0, count);
}
fos.close();
}
}
}
}
}
```
以上是使用 Apache Commons Compress 实现文件压缩与解压的示例代码,你可以根据自己的需求进行修改。
阅读全文