-3

Easiest way to unpack Tar (or BZip+Tar) archive in Java.

Apache Commons Compress has classes for unpacking Tar. But you have to iterate through all archive entries and save each entry's InputStream to file.

Is there way to simple unpack all files from Tar archive "in one line of code"?

Aleks Ya
  • 859
  • 5
  • 15
  • 27

2 Answers2

0

I think your best bet is to launch as a subprocess. These libraries work with filesystem entries. So there is no easy way of doing it in one line of code

ProcessBuilder pb = new ProcessBuilder();
pb.directory(new File("path to your tar"));
pb.command("tar", "-xzvf", "my tar");
pb.start();
bichito
  • 1,406
  • 2
  • 19
  • 23
  • It isn't guaranteed that the tar utility will be available on the machine. I have to use only Java. – Aleks Ya Apr 04 '17 at 17:31
  • then my impression is that you need to write your own library on top apache's compress if you want to avoid future repetitions of this. – bichito Apr 04 '17 at 17:38
0

Plexus Archiver can do it. But it also requires dependencies on plexus-container:

  • org.codehaus.plexus:plexus-archiver:3.4
  • org.codehaus.plexus:plexus-container-default:1.7.1

Example:

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"));
    }
}
Aleks Ya
  • 859
  • 5
  • 15
  • 27