Frage

Wie extrahieren wir ein tar (oder tar.gz oder tar.bz2) Datei in Java?

War es hilfreich?

Lösung

Hinweis: Diese Funktionalität später durch ein eigenes Projekt veröffentlicht wurde, Apache Commons Compress, wie in ein anderes beschrieben beantworten. diese Antwort nicht mehr aktuell ist.


Ich habe keinen Teer API direkt, sondern tar und bzip2 umgesetzt in Ant verwendet; Sie könnten ihre Implementierung ausleihen oder möglicherweise Ant verwenden zu tun, was Sie benötigen.

gzip ist Teil von Java SE (und ich vermute, die Ant Umsetzung das gleiche Modell folgt).

GZIPInputStream ist nur ein InputStream Dekorateur. Sie können wickeln, beispielsweise eine FileInputStream in einem GZIPInputStream und verwenden Sie es auf die gleiche Art und Weise Sie jede InputStream verwenden würde:

InputStream is = new GZIPInputStream(new FileInputStream(file));

(Beachten Sie, dass der GZIPInputStream seine eigenen, interne Puffer hat, so den FileInputStream in einem BufferedInputStream Einwickeln wahrscheinlich die Leistung verringern würde.)

Andere Tipps

Sie können dies tun, mit der Apache Commons Compress Bibliothek. Sie können die 1.2-Version herunterladen von http://mvnrepository.com/artifact/ org.apache.commons / commons-Kompresse / 1.2 .

Hier sind zwei Methoden: eine, die eine Datei und eine anderen unzips, die es untars. Also, für eine Datei tar.gz, müssen Sie zuerst entpacken und danach entpacken Sie es. Bitte beachten Sie, dass die tar-Archiv-Ordner als auch enthält, Fall, in dem sie müssen auf dem lokalen Dateisystem erstellt werden.

Genießen.

/** Untar an input file into an output file.

 * The output file is created in the output folder, having the same name
 * as the input file, minus the '.tar' extension. 
 * 
 * @param inputFile     the input .tar file
 * @param outputDir     the output directory file. 
 * @throws IOException 
 * @throws FileNotFoundException
 *  
 * @return  The {@link List} of {@link File}s with the untared content.
 * @throws ArchiveException 
 */
private static List<File> unTar(final File inputFile, final File outputDir) throws FileNotFoundException, IOException, ArchiveException {

    LOG.info(String.format("Untaring %s to dir %s.", inputFile.getAbsolutePath(), outputDir.getAbsolutePath()));

    final List<File> untaredFiles = new LinkedList<File>();
    final InputStream is = new FileInputStream(inputFile); 
    final TarArchiveInputStream debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", is);
    TarArchiveEntry entry = null; 
    while ((entry = (TarArchiveEntry)debInputStream.getNextEntry()) != null) {
        final File outputFile = new File(outputDir, entry.getName());
        if (entry.isDirectory()) {
            LOG.info(String.format("Attempting to write output directory %s.", outputFile.getAbsolutePath()));
            if (!outputFile.exists()) {
                LOG.info(String.format("Attempting to create output directory %s.", outputFile.getAbsolutePath()));
                if (!outputFile.mkdirs()) {
                    throw new IllegalStateException(String.format("Couldn't create directory %s.", outputFile.getAbsolutePath()));
                }
            }
        } else {
            LOG.info(String.format("Creating output file %s.", outputFile.getAbsolutePath()));
            final OutputStream outputFileStream = new FileOutputStream(outputFile); 
            IOUtils.copy(debInputStream, outputFileStream);
            outputFileStream.close();
        }
        untaredFiles.add(outputFile);
    }
    debInputStream.close(); 

    return untaredFiles;
}

/**
 * Ungzip an input file into an output file.
 * <p>
 * The output file is created in the output folder, having the same name
 * as the input file, minus the '.gz' extension. 
 * 
 * @param inputFile     the input .gz file
 * @param outputDir     the output directory file. 
 * @throws IOException 
 * @throws FileNotFoundException
 *  
 * @return  The {@File} with the ungzipped content.
 */
private static File unGzip(final File inputFile, final File outputDir) throws FileNotFoundException, IOException {

    LOG.info(String.format("Ungzipping %s to dir %s.", inputFile.getAbsolutePath(), outputDir.getAbsolutePath()));

    final File outputFile = new File(outputDir, inputFile.getName().substring(0, inputFile.getName().length() - 3));

    final GZIPInputStream in = new GZIPInputStream(new FileInputStream(inputFile));
    final FileOutputStream out = new FileOutputStream(outputFile);

    IOUtils.copy(in, out);

    in.close();
    out.close();

    return outputFile;
}

Apache Commons VFS unterstützt tar als virtuelles Dateisystem , die unterstützt URLs wie diese tar:gz:http://anyhost/dir/mytar.tar.gz!/mytar.tar!/path/in/tar/README.txt

TrueZip oder sein Nachfolger TrueVFS macht das gleiche ... es ist auch von Maven Zentrale zur Verfügung.

Archiver archiver = ArchiverFactory.createArchiver("tar", "gz");
archiver.extract(archiveFile, destDir);

Abhängigkeit:

 <dependency>
        <groupId>org.rauschig</groupId>
        <artifactId>jarchivelib</artifactId>
        <version>0.5.0</version>
</dependency>

Ich habe gerade versucht, eine Reihe der vorgeschlagenen Libs (TrueZip, Apache Compress), aber kein Glück.

Hier ist ein Beispiel mit Apache Commons VFS:

FileSystemManager fsManager = VFS.getManager();
FileObject archive = fsManager.resolveFile("tgz:file://" + fileName);

// List the children of the archive file
FileObject[] children = archive.getChildren();
System.out.println("Children of " + archive.getName().getURI()+" are ");
for (int i = 0; i < children.length; i++) {
    FileObject fo = children[i];
    System.out.println(fo.getName().getBaseName());
    if (fo.isReadable() && fo.getType() == FileType.FILE
        && fo.getName().getExtension().equals("nxml")) {
        FileContent fc = fo.getContent();
        InputStream is = fc.getInputStream();
    }
}

Und die Maven-Abhängigkeit:

    <dependency>
      <groupId>commons-vfs</groupId>
      <artifactId>commons-vfs</artifactId>
      <version>1.0</version>
    </dependency>

Zusätzlich und bzip2 gzip, Apache Commons Compress API auch tar Unterstützung hat, ursprünglich basierend auf ICE Engineering-Java Tar-Paket , die sowohl API und Standalone-Tool ist.

Was ist mit diesem API für tar-Dateien, diese andere innerhalb Ant für BZIP2 und die Standard ein für GZIP?

Hier ist eine Version basierend auf diese frühere Antwort von Dan Borza dass verwendet Apache Commons Compress und Java NIO (dh Pfad statt File). Es macht auch die Dekomprimierung und entpacken in einem Strom, so dass keine Zwischendatei Schöpfung ist.

public static void unTarGz( Path pathInput, Path pathOutput ) throws IOException {
    TarArchiveInputStream tararchiveinputstream =
        new TarArchiveInputStream(
            new GzipCompressorInputStream(
                new BufferedInputStream( Files.newInputStream( pathInput ) ) ) );

    ArchiveEntry archiveentry = null;
    while( (archiveentry = tararchiveinputstream.getNextEntry()) != null ) {
        Path pathEntryOutput = pathOutput.resolve( archiveentry.getName() );
        if( archiveentry.isDirectory() ) {
            if( !Files.exists( pathEntryOutput ) )
                Files.createDirectory( pathEntryOutput );
        }
        else
            Files.copy( tararchiveinputstream, pathEntryOutput );
    }

    tararchiveinputstream.close();
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top