解压BZIP2归档文件

25

我可以解压zip、gzip和rar文件,但我也需要解压bzip2文件并将它们解档(.tar)。我还没有找到一个好的库来使用。

我正在使用Java和Maven,所以理想情况下,我希望将其包含在POM依赖项中。

你推荐哪些库?

2个回答

42
我能看到的最好选择是Apache Commons Compress,使用这个Maven依赖项。
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-compress</artifactId>
  <version>1.0</version>
</dependency>

以下来自示例

FileInputStream in = new FileInputStream("archive.tar.bz2");
FileOutputStream out = new FileOutputStream("archive.tar");
BZip2CompressorInputStream bzIn = new BZip2CompressorInputStream(in);
final byte[] buffer = new byte[buffersize];
int n = 0;
while (-1 != (n = bzIn.read(buffer))) {
  out.write(buffer, 0, n);
}
out.close();
bzIn.close();

3
你可以使用Apache Commons IO的IOUtils.copyLarge来复制流。 - thSoft

4

请不要忘记使用缓冲流,以获得高达3倍的速度提升

public void decompressBz2(String inputFile, String outputFile) throws IOException {
    var input = new BZip2CompressorInputStream(new <b>BufferedInputStream</b>(new FileInputStream(inputFile)));
    var output = new FileOutputStream(outputFile);
    try (input; output) {
        IOUtils.copy(input, output);
    }
}

decompressBz2("example.bz2", "example.txt");

使用build.gradle.kts文件:

dependencies {
    ...
    implementation("org.apache.commons:commons-compress:1.20")
}

这里有一个严重的区别! - Jire

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接