java编写解压7-ZIP、ACE、ALZ、ZIP、RAR、TAR、ZIP、RAR格式压缩包
时间: 2023-07-10 08:36:24 浏览: 144
Java语言可以使用Apache Commons Compress库来解压7-ZIP、ACE、ALZ、ZIP、RAR、TAR、ZIP、RAR格式压缩包。以下是一个示例代码:
```java
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.compress.compressors.xz.XZCompressorInputStream;
import org.apache.commons.compress.compressors.z.ZCompressorInputStream;
import org.apache.commons.compress.utils.IOUtils;
import java.io.*;
public class Uncompressor {
public static void main(String[] args) throws IOException, ArchiveException {
File input = new File("compressed_file_path");
File outputDir = new File("output_directory_path");
try (InputStream inputStream = new FileInputStream(input);
ArchiveInputStream archiveInputStream = new ArchiveStreamFactory()
.createArchiveInputStream(new BufferedInputStream(inputStream))) {
ArchiveEntry entry;
while ((entry = archiveInputStream.getNextEntry()) != null) {
File outputFile = new File(outputDir, entry.getName());
if (entry.isDirectory()) {
if (!outputFile.isDirectory() && !outputFile.mkdirs()) {
throw new IOException("Failed to create directory " + outputFile);
}
} else {
try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile))) {
IOUtils.copy(archiveInputStream, outputStream);
}
}
}
}
}
}
```
该示例代码可以处理多种压缩包格式,如ZIP、RAR、TAR、GZIP、BZIP2、XZ和Z。你可以根据自己的需要选择要解压的压缩包格式。
阅读全文