2017-04-04 36 views
-3

在Java中解压tar(或BZip + Tar)归档的最简单方法。在Java中轻松解包整个Tar

Apache Commons Compress有解包焦油的类。但是您必须迭代所有存档条目并将每个条目的InputStream保存到文件。

是否有方法可以简单地从Tar存档中将所有文件解压缩到“一行代码”中?

回答

0

我认为你最好的选择是作为一个子进程启动。这些库适用于文件系统条目。所以在代码

ProcessBuilder pb = new ProcessBuilder(); 
pb.directory(new File("path to your tar")); 
pb.command("tar", "-xzvf", "my tar"); 
pb.start(); 
+0

不能保证tar实用程序在计算机上可用。我只能使用Java。 –

+0

那么我的印象是,如果你想避免将来重复这个,你需要在顶部的apache的compress上编写自己的库。 – efekctive

0

Plexus Archiver可以做到一条线做的没有简单的方法。 但它也需要依赖于plexus-container

  • org.codehaus.plexus:丛存档器:3.4
  • org.codehaus.plexus:丛容器默认:1.7.1

示例:

import org.codehaus.plexus.archiver.tar.TarUnArchiver; 
import org.codehaus.plexus.logging.Logger; 
import org.codehaus.plexus.logging.console.ConsoleLogger; 
import org.junit.Test; 
import java.io.File; 
import java.io.IOException; 
import java.nio.file.Files; 
import static org.hamcrest.MatcherAssert.assertThat; 
import static org.hamcrest.Matchers.arrayContaining; 

public class UnpackTarTest { 

    @Test 
    public void wholeTarAtOnce() throws IOException { 
     File srcFile = new File(getClass().getResource("my.tar").getFile()); 
     File destDir = Files.createTempDirectory("UnpackTarTest_").toFile(); 
     destDir.deleteOnExit(); 

     final TarUnArchiver ua = new TarUnArchiver(); 
     ua.setSourceFile(srcFile); 
     ua.enableLogging(new ConsoleLogger(Logger.LEVEL_DEBUG, "console_logger")); 
     ua.setDestDirectory(destDir); 
     ua.extract(); 
     assertThat(destDir.list(), arrayContaining("mytar")); 
    } 
}