Documentation

Extraction masterclass

Fast, safe, and honest about what happened.

7-Zip-JBinding is a thin JNI layer over the same native engine as the 7z command line — extraction is essentially as fast as 7-Zip itself, as long as the calling code lets it. An archive is also untrusted input, and the engine reports failures in more than one way. This page shows how to get all three right — speed, safety and error handling — and ends with complete, tested examples that put it together.

TL;DR — Extract everything in one call toinArchive.extract(indices, false, callback) with the indices ascending. In the callback open each output file once in getStream(), keep appending to abuffered stream in write(), and close it in setOperationResult(). Make every decision before streaming, and do no work at all per chunk.

1. The big one: don’t extract solid archives item-by-item

7z archives are usually solid: many files are compressed together into one continuous stream, which is what gives 7z its great ratio. The price is that to reach file n the engine must decompress everything before it. That is fine when you extract in order in a single pass — the block is streamed exactly once.

It becomes a disaster if you loop over items and extract them one at a time withinArchive.extractSlow(...) (or a per-item extract call). Each call restarts decompression from the beginning of the solid block, so unpackingk files re-decompresses the block k times:

✗ O(n²) — re-decompresses every time
for (int i = 0; i < count; i++) {
    inArchive.extractSlow(i, out); // restarts the solid block each iteration
}
✓ O(n) — one pass over the solid block
int[] all = ...; // indices of every file
inArchive.extract(all, false, callback); // engine streams the block once

On a solid archive with thousands of files this is the difference between seconds and an hour. Always hand the full list of indices to a singleextract(int[], false, callback) call and let the engine walk the archive once. (extractSlow is a convenience for pulling out one item; it is the wrong tool for bulk extraction.)

The performance checklist

The engine runs at native speed; extraction is only as fast as the least disciplined line in your callback. Each rule below removes a specific way of wasting the engine's work.

  1. One extract() call, every file, indices ascending. A solid block is decompressed once and the files fall out in order. Out-of-order or repeated requests re-decompress it.
  2. Never extractSlow() in a loop. It exists to pull out a single item.
  3. Decide first, stream second. Property lookups (PATH,IS_FOLDER, attributes, …) are native calls. Do them once per item in a planning pass — never inside getStream() or write().
  4. Open once, append, close once. write() is called many times per file; re-opening or seeking on each call turns a linear copy into an avalanche of system calls.
  5. Buffer the output — a BufferedOutputStream with a generous buffer (the example uses 64 KB). The engine's chunks are small; without a buffer each one is a system call.
  6. Keep the hot path empty. No logging, hashing, flushing or progress printing per chunk. Progress belongs in setCompleted(), which the engine calls for you.
  7. Open the archive from a file. RandomAccessFileInStream lets the engine seek; loading the whole archive into a byte array first costs memory and time for nothing.
  8. One archive per thread. IInArchive is not thread-safe, and the codecs already use several cores internally. Parallelise across archives, never within one.
  9. Only checking? Use test mode. extract(indices, true, callback) verifies items without writing a byte.
  10. Measure on the real archive. Solid vs non-solid, item count and item size change the picture completely; the engine tells you nothing about your callback's cost.

2. Plan, then stream, then account

The engine drives extraction through your IArchiveExtractCallback. An archive is untrusted input, so the example keeps three jobs strictly apart: plan (decide what may be written, and where — before a single byte lands), stream (the callback, which only moves bytes), and account (say honestly what happened). Each has its own rules.

Plan — the safety rules

Stream — the fast path

Account — errors arrive on three channels

3. One archive, one thread

A single IInArchive instance and its extraction are not thread-safe, and the native codecs already use multiple cores internally where it helps. Don’t try to speed a single archive up by extracting different items from several threads — it will not go faster and can corrupt state. To process many separate archives in parallel, give each thread its own IInArchive.

Complete example: extract a whole archive to a directory

This puts all of the above together: a plan phase validates every entry (traversal, links, nameless entries, OS-specific names, existing files) and creates the directories, oneextract() call streams every approved file, and a report with a trustworthy exit code closes the run. It is a real program from the test suite — the output shown below is verified on every release, and its safety rules are pinned down by a dedicated test class.

ExtractToFolder.java verified by ExtractToFolderTest
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import net.sf.sevenzipjbinding.ExtractAskMode;
import net.sf.sevenzipjbinding.ExtractOperationResult;
import net.sf.sevenzipjbinding.IArchiveExtractCallback;
import net.sf.sevenzipjbinding.IInArchive;
import net.sf.sevenzipjbinding.ISequentialOutStream;
import net.sf.sevenzipjbinding.PropID;
import net.sf.sevenzipjbinding.ReportExtractResultIndexType;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;

/**
 * Extract a whole archive into a directory - fast, safe, and honest about what happened.
 *
 * <p><b>Performance.</b> 7-Zip-JBinding is a thin layer over the native 7-Zip engine, so extraction
 * runs at the engine's own speed - as long as the calling code lets it. What makes this example fast:
 * <ul>
 *   <li><b>One {@code extract()} call for all files, indices ascending.</b> Solid archives (7z by
 *       default) compress many files into one continuous stream; the engine decompresses it once and
 *       hands the files out as they appear. Requesting files one at a time ({@code extractSlow} in a
 *       loop) restarts that stream for every request - O(n^2), the difference between seconds and
 *       an hour on a large archive.</li>
 *   <li><b>A callback that only moves bytes.</b> {@code getStream()} opens the output file once;
 *       {@code write()} is called many times per file and does nothing but append to a buffered
 *       stream; {@code setOperationResult()} closes once. No re-opening, no seeking, no logging, no
 *       property lookups per chunk - the hot path stays empty.</li>
 *   <li><b>Every decision made before streaming.</b> Property lookups (paths, kinds, attributes) are
 *       native calls; they happen once per item in the plan phase, never inside the write loop.</li>
 *   <li><b>Buffered output</b> with a generous buffer, so the engine's many small chunks do not each
 *       become a system call.</li>
 *   <li><b>One archive, one thread.</b> An {@code IInArchive} is not thread-safe, and the codecs
 *       already use several cores internally. Parallelise across archives, never within one.</li>
 * </ul>
 *
 * <p><b>Safety and honesty.</b> An archive is untrusted input, so the example works in three separate
 * phases, and the separation is the point:
 * <ol>
 *   <li><b>Plan</b> - look at every item and decide, before a single byte is written, whether and
 *       where it may go. All the safety rules live here: path traversal, links, special files,
 *       nameless entries.</li>
 *   <li><b>Stream</b> - the single {@code extract()} call and the byte-moving callback.</li>
 *   <li><b>Account</b> - collect every problem, keep going where that is safe, and finish with a
 *       report and an exit code you can trust in a script.</li>
 * </ol>
 *
 * <p>Failures reach you on three channels. An exception you throw from the callback is saved and
 * re-thrown from {@code extract()}. But a broken item (CRC error, truncated data, encrypted data
 * without a password, ...) is reported per item as a non-OK {@link ExtractOperationResult} <em>with no
 * exception at all</em> - {@code extract()} returns normally and continues with the next item. And a
 * problem that belongs to no single item - typically a solid block that fails to decode after every
 * requested file was already written - arrives in {@code reportExtractResult()}, again without an
 * exception. Code that only catches exceptions silently loses the last two.
 */
public class ExtractToFolder {

    // =============================================================================================
    // Result types
    // =============================================================================================

    /** One item that could not be extracted as intended. Never fatal: the other items still extract. */
    public static final class ItemError {
        public final int index;
        public final String path;    // the item's path as stored in the archive
        public final String kind;    // what went wrong, in plain words
        public final Throwable cause; // null when the engine reported a result without an exception

        ItemError(int index, String path, String kind, Throwable cause) {
            this.index = index;
            this.path = path;
            this.kind = kind;
            this.cause = cause;
        }

        @Override
        public String toString() {
            return "[#" + index + " " + path + "] " + kind + (cause != null ? ": " + cause.getMessage() : "");
        }
    }

    /** Everything a caller needs to decide what to do next. */
    public static final class Report {
        public final List<ItemError> itemErrors;
        public final int filesPlanned;       // files the plan phase approved for extraction
        public final int filesExtracted;     // files written completely and closed successfully
        public final int filesNotExtracted;  // approved files that never got a verdict (see writeFailed)
        public final boolean writeFailed;    // an output write failed (disk full, ...) and extraction stopped
        public final SevenZipException archiveError; // extract() failed for a reason we did not cause

        Report(List<ItemError> itemErrors, int filesPlanned, int filesExtracted, int filesNotExtracted,
                boolean writeFailed, SevenZipException archiveError) {
            this.itemErrors = Collections.unmodifiableList(itemErrors);
            this.filesPlanned = filesPlanned;
            this.filesExtracted = filesExtracted;
            this.filesNotExtracted = filesNotExtracted;
            this.writeFailed = writeFailed;
            this.archiveError = archiveError;
        }

        public boolean isClean() {
            return itemErrors.isEmpty() && archiveError == null && filesNotExtracted == 0;
        }
    }

    // =============================================================================================
    // The extractor: plan -> stream -> account
    // =============================================================================================

    public static class Extractor implements IArchiveExtractCallback {
        private static final boolean WINDOWS = File.separatorChar == '\\';
        /** The engine delivers data in many small chunks; batching them keeps system calls rare. */
        private static final int OUTPUT_BUFFER_SIZE = 64 * 1024;

        private final IInArchive archive;
        private final File outputDir;      // canonical, absolute, exists, is a directory
        private final String fallbackName; // name for entries the archive does not name (see below)

        // plan
        private final Map<Integer, File> targets = new HashMap<Integer, File>();
        private final Map<Integer, String> displayNames = new HashMap<Integer, String>();
        private final List<ItemError> itemErrors = new ArrayList<ItemError>();
        private int filesPlanned;

        // stream (state of the item currently being written)
        private int currentIndex;
        private File currentFile;
        private OutputStream currentOut;
        private boolean currentRecorded;
        private int currentHash;
        private long currentSize;

        // account
        private int filesExtracted;
        private int filesAccounted; // files that reached a verdict: extracted, or an error recorded
        private boolean writeFailed;

        /**
         * @param archive     an open archive
         * @param archiveName the archive's file name; only used to name entries that carry no name
         * @param outputDir   where to extract to; created if missing
         * @throws IOException if the output directory cannot be created or resolved
         */
        public Extractor(IInArchive archive, String archiveName, File outputDir) throws IOException {
            this.archive = archive;
            // Resolve the output directory ONCE, up front. Every later safety check compares against
            // this canonical form, so relative paths ("", ".", "out") and symlinked directories all
            // behave. The root directory itself is a legal output directory.
            File dir = outputDir.getAbsoluteFile();
            if (!dir.isDirectory() && !dir.mkdirs()) {
                throw new IOException("Output directory cannot be created: " + dir);
            }
            this.outputDir = dir.getCanonicalFile();
            this.fallbackName = fallbackName(archiveName);
        }

        // -------------------------------------------------------------------------------------
        // Phase 1: plan. Decide for every item what it is and where it may go - nothing is written.
        // -------------------------------------------------------------------------------------

        private void plan() {
            int count;
            try {
                count = archive.getNumberOfItems();
            } catch (SevenZipException e) {
                itemErrors.add(new ItemError(-1, "", "cannot read the item count", e));
                return;
            }
            for (int i = 0; i < count; i++) {
                try {
                    planItem(i);
                } catch (Exception e) {
                    // A damaged archive can make even a property lookup fail; that is one bad item,
                    // not a reason to abandon the rest.
                    itemErrors.add(new ItemError(i, "#" + i, "cannot read item properties", e));
                }
            }
        }

        private void planItem(int index) throws SevenZipException, IOException {
            String path = stringProperty(index, PropID.PATH);
            // Properties are optional in some formats: a missing IS_FOLDER is null, never assume Boolean.
            boolean directory = Boolean.TRUE.equals(archive.getProperty(index, PropID.IS_FOLDER));

            // Links and special files are skipped by design. A symbolic link extracted as a link can
            // point anywhere - including outside the output directory - and a later item written
            // "through" it would escape. Extracting it as a file instead would silently produce a file
            // containing the link target, which is not what anyone wants. Skip, and say so.
            String special = directory ? null : specialEntryKind(index);
            if (special != null) {
                itemErrors.add(new ItemError(index, path, "skipped: " + special + " entries are not extracted", null));
                return;
            }

            List<String> parts;
            try {
                parts = safeComponents(path, WINDOWS);
            } catch (IllegalArgumentException unsafe) {
                itemErrors.add(new ItemError(index, path, "blocked: " + unsafe.getMessage(), null));
                return;
            }
            String displayName = path;
            if (parts.isEmpty()) {
                if (directory) {
                    return; // the archive root - it exists already
                }
                // Single-stream formats (gzip, bzip2, xz, ...) and some zip/tar entries store no name.
                // Without a name the target would be the output directory itself - and writing a file
                // over a directory is exactly what must never happen. Do what the 7-Zip command line
                // does: derive a name from the archive's file name.
                parts = safeComponents(fallbackName, WINDOWS);
                displayName = fallbackName;
            }

            File target = new File(outputDir, join(parts));
            // Belt and braces: the components above are already clean, but the canonical path also
            // resolves symlinks that may already exist inside the output directory. If "a" is a link
            // to /etc, then "a/passwd" must still be refused.
            if (!isInside(outputDir, target.getCanonicalFile())) {
                itemErrors.add(new ItemError(index, path, "blocked: resolves outside the output directory", null));
                return;
            }

            if (directory) {
                if (!target.isDirectory() && !target.mkdirs()) {
                    itemErrors.add(new ItemError(index, path, "cannot create directory", null));
                }
                return; // directories - including empty ones - are created right here
            }
            targets.put(index, target);
            displayNames.put(index, displayName);
            filesPlanned++;
        }

        /** Names the kind of entry that must not be written as a plain file, or null for a regular file. */
        private String specialEntryKind(int index) throws SevenZipException {
            if (!stringProperty(index, PropID.SYM_LINK).isEmpty()) {
                return "symbolic link";
            }
            if (!stringProperty(index, PropID.HARD_LINK).isEmpty()) {
                return "hard link"; // carries a regular file mode, so only the property reveals it
            }
            Object attributes = archive.getProperty(index, PropID.ATTRIBUTES);
            if (attributes instanceof Integer && (((Integer) attributes) & 0x400) != 0) {
                return "reparse point"; // FILE_ATTRIBUTE_REPARSE_POINT: a Windows link or junction
            }
            int mode = unixMode(index);
            if (mode >= 0) {
                int type = mode & 0xF000; // S_IFMT; zero when the format stores permissions only
                if (type != 0 && type != 0x8000 /* S_IFREG */ && type != 0x4000 /* S_IFDIR */) {
                    return type == 0xA000 /* S_IFLNK */ ? "symbolic link" : "device, pipe or socket";
                }
            }
            return null;
        }

        /** The Unix mode bits, from POSIX_ATTRIB or from the high half of ATTRIBUTES, or -1 if unknown. */
        private int unixMode(int index) throws SevenZipException {
            Object posix = archive.getProperty(index, PropID.POSIX_ATTRIB);
            if (posix instanceof Integer) {
                return (Integer) posix;
            }
            // Zip and 7z store Unix bits in the upper 16 bits of the Windows attributes when the
            // 0x8000 "unix extension" flag is set - the 7-Zip convention.
            Object attributes = archive.getProperty(index, PropID.ATTRIBUTES);
            if (attributes instanceof Integer && (((Integer) attributes) & 0x8000) != 0) {
                return ((Integer) attributes) >>> 16;
            }
            return -1;
        }

        private String stringProperty(int index, PropID propID) throws SevenZipException {
            String value = archive.getStringProperty(index, propID);
            return value == null ? "" : value;
        }

        // -------------------------------------------------------------------------------------
        // Phase 2: stream. One extract() call; the callback opens once, appends, closes once.
        // -------------------------------------------------------------------------------------

        /** Where the bytes of one file go. Override to redirect output (tests use this). */
        protected OutputStream openOutput(File file) throws IOException {
            return new BufferedOutputStream(new FileOutputStream(file), OUTPUT_BUFFER_SIZE);
        }

        public ISequentialOutStream getStream(int index, ExtractAskMode mode) throws SevenZipException {
            currentIndex = index;
            currentFile = null;
            currentOut = null;
            currentRecorded = false;
            if (mode != ExtractAskMode.EXTRACT) {
                return null; // a test or skip pass wants no data
            }
            if (writeFailed) {
                return null; // once the disk failed, writing more can only fail again; skip, and count
            }
            File target = targets.get(index);
            if (target == null) {
                return null; // not approved by the plan (the engine is only given approved indices)
            }
            // Never overwrite silently. This is 7-Zip's "-aos" (skip existing) policy; overwriting is a
            // deliberate, documented decision an application may make - not a default.
            if (target.exists()) {
                record(target.isDirectory() ? "a directory is in the way" : "already exists - not overwritten", null);
                return null;
            }
            File parent = target.getParentFile();
            if (parent != null && !parent.isDirectory() && !parent.mkdirs()) {
                record("cannot create parent directory " + parent, null);
                return null;
            }
            try {
                currentOut = openOutput(target); // opened ONCE per file
            } catch (IOException e) {
                record("cannot create output file", e);
                return null;
            }
            currentFile = target;
            currentHash = 0;
            currentSize = 0;

            return new ISequentialOutStream() {
                public int write(byte[] data) throws SevenZipException {
                    try {
                        currentOut.write(data); // called many times per file: just append
                    } catch (IOException e) {
                        // Never claim to have consumed bytes that were not written - that is silent
                        // corruption. Record the real cause, remember that the disk is unusable, and
                        // throw; the engine saves the exception and re-throws it from extract().
                        record("cannot write output file", e);
                        writeFailed = true;
                        throw new SevenZipException("Cannot write " + currentFile + ": " + e.getMessage(), e);
                    }
                    currentHash ^= Arrays.hashCode(data); // demo checksum shared by all snippets here
                    currentSize += data.length;
                    return data.length; // the contract: return the number of bytes consumed
                }
            };
        }

        public void prepareOperation(ExtractAskMode mode) {
            // Called before each item with the operation kind (extract/test/skip). Nothing to do here.
        }

        public void setOperationResult(ExtractOperationResult result) throws SevenZipException {
            // The engine is done with the current item: close first, and keep a close failure aside.
            // A failed close must be reported, but it must never replace the item's primary error.
            IOException closeError = null;
            if (currentOut != null) {
                try {
                    currentOut.close(); // flushes the last buffered block
                } catch (IOException e) {
                    closeError = e;
                }
                currentOut = null;
            }
            if (currentFile == null && !currentRecorded) {
                // Nothing was written for this item. After a disk failure that is our own doing, and
                // the file is counted as not extracted rather than judged. Otherwise the engine never
                // asked for the data at all - it does that when it cannot decode an item, such as
                // encrypted data without a password - and the verdict it gives here is the only trace
                // of the failure.
                if (writeFailed || result == ExtractOperationResult.OK || !targets.containsKey(currentIndex)) {
                    return;
                }
                filesAccounted++;
                record(engineVerdict(result), null);
                return;
            }
            filesAccounted++;

            if (currentRecorded) {
                discardPartialFile(); // our own open/write failure already speaks for this item
                return;
            }
            if (result != ExtractOperationResult.OK) {
                // This is the second failure channel: the engine judged the item bad (CRC error, data
                // error, ...) and told us here - with no exception. Record it, or it is lost.
                record(engineVerdict(result), null);
                if (closeError != null) {
                    record("cannot close output file", closeError);
                }
                discardPartialFile();
                return;
            }
            if (closeError != null) {
                // The engine was happy, but the final flush failed: the file on disk is truncated.
                record("cannot flush output file", closeError);
                discardPartialFile();
                return;
            }

            filesExtracted++;
            Object modified = archive.getProperty(currentIndex, PropID.LAST_MODIFICATION_TIME);
            if (modified instanceof Date) {
                currentFile.setLastModified(((Date) modified).getTime()); // cosmetic: failure is not an error
            }
            System.out.println(String.format("%9X | %10s | %s", currentHash, currentSize,
                    displayNames.get(currentIndex)));
        }

        /**
         * The third channel: a result the engine reports outside of any single item's verdict - for
         * a 7z archive, a solid block that failed to decode after all requested files were written.
         * The default implementation ignores it, so it must be overridden to be heard.
         */
        @Override
        public void reportExtractResult(ReportExtractResultIndexType indexType, int index,
                ExtractOperationResult result) {
            if (result == ExtractOperationResult.OK) {
                return;
            }
            String where = indexType == ReportExtractResultIndexType.BLOCK_INDEX ? "block #" + index
                    : indexType + " #" + index;
            itemErrors.add(new ItemError(-1, where, "engine reported " + result + " for this part of the archive", null));
        }

        public void setTotal(long total) {
            // Progress: total bytes to process. Wire this and setCompleted() to a progress bar.
        }

        public void setCompleted(long completed) {
        }

        /** The engine's verdict in words, plus the one hint that most often explains it. */
        private String engineVerdict(ExtractOperationResult result) {
            String verdict = "engine reported " + result;
            try {
                if (Boolean.TRUE.equals(archive.getProperty(currentIndex, PropID.ENCRYPTED))) {
                    verdict += " (the item is encrypted: extracting it needs a password, see ICryptoGetTextPassword)";
                }
            } catch (SevenZipException e) {
                // the verdict on its own is still correct
            }
            return verdict;
        }

        /**
         * A file that failed halfway must not stay on disk: a script that only checks "does the file
         * exist" would otherwise trust a truncated or corrupt result. Pre-existing files are never
         * touched - they were refused before anything was opened, so {@code currentFile} is null.
         */
        private void discardPartialFile() {
            if (currentFile != null) {
                currentFile.delete();
            }
        }

        private void record(String kind, Throwable cause) {
            currentRecorded = true;
            String path = "#" + currentIndex;
            try {
                path = stringProperty(currentIndex, PropID.PATH);
            } catch (SevenZipException e) {
                // keep the index as the name
            }
            itemErrors.add(new ItemError(currentIndex, path, kind, cause));
        }

        // -------------------------------------------------------------------------------------
        // Phase 3: run the phases and account for everything.
        // -------------------------------------------------------------------------------------

        /** Plan, stream, and account. Never throws: everything ends up in the {@link Report}. */
        public Report extractAll() {
            plan();
            int[] files = new int[targets.size()];
            int n = 0;
            for (int index = 0; n < files.length; index++) {
                if (targets.containsKey(index)) {
                    files[n++] = index;
                }
            }
            SevenZipException archiveError = null;
            try {
                if (files.length > 0) {
                    archive.extract(files, false, this); // ONE call, ascending indices: one pass, O(n)
                }
            } catch (SevenZipException e) {
                // If we made the engine stop by throwing from write(), this is our own exception coming
                // back - already recorded against its item. Anything else is a genuine archive error.
                if (!writeFailed) {
                    archiveError = e;
                }
            } catch (RuntimeException e) {
                archiveError = new SevenZipException("Unexpected error during extraction: " + e, e);
            } finally {
                if (currentOut != null) {
                    // The engine stopped without giving the item in progress a verdict. Never leak the
                    // handle, never leave the half-written file, and never leave the item unaccounted.
                    closeQuietly();
                    discardPartialFile();
                    if (!currentRecorded) {
                        record("extraction stopped before this file was complete", null);
                    }
                    filesAccounted++;
                }
            }
            return new Report(itemErrors, filesPlanned, filesExtracted, filesPlanned - filesAccounted,
                    writeFailed, archiveError);
        }

        private void closeQuietly() {
            OutputStream out = currentOut;
            currentOut = null;
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // the file is already reported as broken; only the handle matters here
                }
            }
        }

        // -------------------------------------------------------------------------------------
        // Path rules. Small, explicit, and testable on their own.
        // -------------------------------------------------------------------------------------

        /**
         * Splits an archive path into clean components. Both separators are accepted (7-Zip reports
         * the native one), empty and "." components are dropped, and anything that could leave the
         * output directory or misbehave on the current OS is rejected with the reason.
         */
        static List<String> safeComponents(String entryPath, boolean windowsRules) {
            List<String> parts = new ArrayList<String>();
            for (String part : entryPath.split("[/\\\\]")) {
                if (part.isEmpty() || part.equals(".")) {
                    continue;
                }
                if (part.equals("..")) {
                    throw new IllegalArgumentException("path contains '..'");
                }
                for (int i = 0; i < part.length(); i++) {
                    char c = part.charAt(i);
                    if (c < 0x20) {
                        throw new IllegalArgumentException("path contains a control character");
                    }
                    if (windowsRules && "<>:\"|?*".indexOf(c) >= 0) {
                        throw new IllegalArgumentException("path contains '" + c + "', illegal on Windows");
                    }
                }
                if (windowsRules) {
                    if (part.endsWith(" ") || part.endsWith(".")) {
                        throw new IllegalArgumentException("Windows drops a trailing space or dot from '" + part + "'");
                    }
                    String base = part.toUpperCase(Locale.ROOT);
                    int dot = base.indexOf('.');
                    if (dot >= 0) {
                        base = base.substring(0, dot); // "CON.txt" is still the console device
                    }
                    if (base.matches("CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9]")) {
                        throw new IllegalArgumentException("'" + part + "' is a reserved Windows device name");
                    }
                }
                parts.add(part);
            }
            return parts;
        }

        /** True if {@code candidate} is {@code root} or lies below it. Both must be canonical. */
        static boolean isInside(File root, File candidate) {
            String rootPath = root.getPath();
            String path = candidate.getPath();
            if (path.equals(rootPath)) {
                return true;
            }
            String prefix = rootPath.endsWith(File.separator) ? rootPath : rootPath + File.separator;
            return path.startsWith(prefix);
        }

        /**
         * The name 7-Zip gives an unnamed entry, derived from the archive's file name: strip the
         * compression extension ("data.gz" -> "data"), turn the tar shorthands into ".tar"
         * ("backup.tgz" -> "backup.tar"), and append "~" when there is nothing to strip.
         */
        static String fallbackName(String archiveName) {
            String lower = archiveName.toLowerCase(Locale.ROOT);
            for (String shorthand : new String[] { ".tgz", ".tpz", ".tbz", ".tbz2", ".txz", ".tlz", ".taz" }) {
                if (lower.endsWith(shorthand)) {
                    return archiveName.substring(0, archiveName.length() - shorthand.length()) + ".tar";
                }
            }
            int dot = archiveName.lastIndexOf('.');
            return dot > 0 ? archiveName.substring(0, dot) : archiveName + "~";
        }

        private static String join(List<String> parts) {
            StringBuilder sb = new StringBuilder();
            for (String part : parts) {
                if (sb.length() > 0) {
                    sb.append(File.separatorChar);
                }
                sb.append(part);
            }
            return sb.toString();
        }
    }

    // =============================================================================================
    // Command line
    // =============================================================================================

    /** Prints every problem, one line each, then the single most useful stack trace. */
    public static void printReport(Report report) {
        if (report.isClean()) {
            return;
        }
        System.err.println("=== extraction problems ===");
        for (ItemError error : report.itemErrors) {
            System.err.println("  " + error);
        }
        if (report.filesNotExtracted > 0) {
            System.err.println("  " + report.filesNotExtracted + " of " + report.filesPlanned + " files not extracted"
                    + (report.writeFailed ? " because writing had already failed" : " - the engine delivered no data for them"));
        }
        if (report.archiveError != null) {
            System.err.println("  archive error, extraction stopped: " + report.archiveError.getMessage());
        }
        Throwable primary = report.archiveError;
        for (int i = 0; primary == null && i < report.itemErrors.size(); i++) {
            primary = report.itemErrors.get(i).cause;
        }
        if (primary instanceof SevenZipException) {
            ((SevenZipException) primary).printStackTraceExtended(); // includes every saved cause
        } else if (primary != null) {
            primary.printStackTrace();
        }
    }

    /** @return the process exit code: 0 = everything extracted, 1 = problems, 2 = wrong usage */
    public static int run(String[] args) {
        if (args.length != 2) {
            System.err.println("Usage: java ExtractToFolder <archive> <output-directory>");
            return 2;
        }
        File archiveFile = new File(args[0]);
        try (RandomAccessFile file = new RandomAccessFile(archiveFile, "r");
                IInArchive archive = SevenZip.openInArchive(null, // null: detect the format
                        new RandomAccessFileInStream(file))) {
            Extractor extractor = new Extractor(archive, archiveFile.getName(), new File(args[1]));

            System.out.println("   Hash   |    Size    | Filename");
            System.out.println("----------+------------+---------");

            Report report = extractor.extractAll();
            printReport(report);
            return report.isClean() ? 0 : 1;
        } catch (SevenZipException e) {
            // Reached when the archive cannot be opened - or closed: hence the neutral wording.
            System.err.println("Archive error: " + e.getMessage());
            e.printStackTraceExtended();
            return 1;
        } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());
            return 1;
        }
    }

    public static void main(String[] args) {
        System.exit(run(args));
    }
}
Output
   Hash   |    Size    | Filename
----------+------------+---------
 C1FD1029 |       4481 | file1.txt
 8CB12E6A |         75 | file2.txt
 E8EEC7F4 |          6 | folder/file in folder.txt

More runnable examples are on the Code snippets page.

Bonus: extract a wrapped archive (.tar.gz) in one go

A .tar.gz is not one archive but two: a GZip stream whose single item is a.tar, which in turn holds the real files. So unwrapping it is always two open/extract steps — open the outer GZip, pull out the inner .tar, then open that. The decision is where the intermediate archive goes:

The example below shows the first two. The same pattern works for any nesting (.cpio.gz, a .zip inside a .7z, …).

Streams, done right. This is a master-class example, not a copy-paste starter, so it treats streams with the care production code needs: every Closeable is managed with try-with-resources, and a failing close() on the write path (say the last buffered block can't be flushed because the disk is full) is allowed to propagate — never swallowed. A swallowed close() is silent data corruption.
ExtractNestedArchive.java verified by ExtractNestedArchiveTest
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;

import net.sf.sevenzipjbinding.ExtractAskMode;
import net.sf.sevenzipjbinding.ExtractOperationResult;
import net.sf.sevenzipjbinding.IArchiveExtractCallback;
import net.sf.sevenzipjbinding.IInArchive;
import net.sf.sevenzipjbinding.IInStream;
import net.sf.sevenzipjbinding.ISequentialOutStream;
import net.sf.sevenzipjbinding.PropID;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.impl.RandomAccessFileOutStream;
import net.sf.sevenzipjbinding.util.ByteArrayStream;

/**
 * Extract a WRAPPED archive - one archive nested inside another, like {@code .tar.gz} - in one go.
 *
 * A {@code .tar.gz} is a GZip stream that contains exactly one item: a {@code .tar} archive, which
 * in turn contains the real files. So "extracting" it is two open/extract steps:
 *   1. open the OUTER archive (GZip) and pull out its single item (the inner {@code .tar});
 *   2. open that inner {@code .tar} and read the actual files.
 *
 * WHERE the intermediate {@code .tar} goes gives you three options:
 *   - {@link #extractInMemory}   - keep the inner archive in a {@link ByteArrayStream}. No temp file;
 *                                  simplest and fast, as long as the inner archive fits in memory.
 *   - {@link #extractViaTempFile} - stream the inner archive to a temporary file and reopen it from
 *                                  disk. Bounded memory, the safe default for a huge inner archive.
 *   - A third, advanced option avoids materialising the inner archive at all: decompress the GZip on
 *     one thread and let the {@code .tar} reader pull those bytes on demand through a small in-memory
 *     pipe (with a look-behind cache, because the tar reader seeks). It is genuinely tricky, so it is
 *     not shown here - see the test {@code ExtractNestedArchiveStreamingTest} for a working proof.
 *
 * Note the stream handling below: everything Closeable is managed with try-with-resources, so a
 * failing {@code close()} on the WRITE path (e.g. the last block cannot be flushed - disk full) is
 * NOT swallowed but propagates as it must; a swallowed close is silent data corruption.
 *
 * The same idea works for any nesting (e.g. {@code .cpio.gz}, a {@code .zip} inside a {@code .7z}, ...).
 */
public class ExtractNestedArchive {

    /** Read EVERY file of an already-opened archive in a single pass and print a verifiable table. */
    private static void listInnerContent(IInArchive innerArchive) throws SevenZipException {
        int count = innerArchive.getNumberOfItems();
        int[] items = new int[count]; // NB: for a real unwrap you'd usually skip folders
        for (int i = 0; i < count; i++) {
            items[i] = i;
        }
        innerArchive.extract(items, false, new IArchiveExtractCallback() {
            private int hash;
            private long size;
            private int index;

            public ISequentialOutStream getStream(int i, ExtractAskMode mode) {
                index = i;
                hash = 0;
                size = 0;
                if (mode != ExtractAskMode.EXTRACT) {
                    return null;
                }
                return new ISequentialOutStream() {
                    public int write(byte[] data) {
                        hash ^= Arrays.hashCode(data); // just to make the example verifiable
                        size += data.length;
                        return data.length; // return the number of bytes consumed
                    }
                };
            }

            public void setOperationResult(ExtractOperationResult result) throws SevenZipException {
                if (result != ExtractOperationResult.OK) {
                    throw new SevenZipException("Extraction failed: " + result);
                }
                boolean folder = ((Boolean) innerArchive.getProperty(index, PropID.IS_FOLDER)).booleanValue();
                if (!folder) {
                    System.out.println(String.format("%9X | %10s | %s", hash, size,
                            innerArchive.getStringProperty(index, PropID.PATH)));
                }
            }

            public void prepareOperation(ExtractAskMode extractAskMode) {
            }

            public void setCompleted(long completeValue) {
            }

            public void setTotal(long total) {
            }
        });
    }

    /** Variant 1: unwrap fully in memory - the inner archive lives in a ByteArrayStream, no temp file. */
    public static void extractInMemory(String wrappedArchive) throws SevenZipException, IOException {
        try (RandomAccessFile outerFile = new RandomAccessFile(wrappedArchive, "r");
                IInArchive outer = SevenZip.openInArchive(null, new RandomAccessFileInStream(outerFile));
                ByteArrayStream innerData = new ByteArrayStream(Integer.MAX_VALUE)) {

            // A GZip/BZip2/XZ stream holds exactly ONE item - the inner archive. Decompress it to memory.
            checkOk(outer.extractSlow(firstFileItem(outer), innerData));

            // Reopen that in-memory data as an archive and read the real files.
            innerData.rewind();
            try (IInArchive inner = SevenZip.openInArchive(null, (IInStream) innerData)) {
                listInnerContent(inner);
            }
        }
    }

    /** Variant 2: unwrap through a temporary file - bounded memory, good for a huge inner archive. */
    public static void extractViaTempFile(String wrappedArchive) throws SevenZipException, IOException {
        File tempTar = File.createTempFile("sevenzipjbinding-inner-", ".tmp");
        try {
            // One handle for both writing the inner archive and reading it back. try-with-resources
            // guarantees close() runs - and, crucially, its IOException is NOT swallowed: a failed
            // flush of the final block (e.g. disk full) must surface, or we'd read a truncated archive.
            try (RandomAccessFile innerFile = new RandomAccessFile(tempTar, "rw")) {
                try (RandomAccessFile outerFile = new RandomAccessFile(wrappedArchive, "r");
                        IInArchive outer = SevenZip.openInArchive(null,
                                new RandomAccessFileInStream(outerFile))) {
                    checkOk(outer.extractSlow(firstFileItem(outer),
                            new RandomAccessFileOutStream(innerFile)));
                }
                // Reopen the temp file (RandomAccessFileInStream seeks as needed) and read it.
                try (IInArchive inner = SevenZip.openInArchive(null,
                        new RandomAccessFileInStream(innerFile))) {
                    listInnerContent(inner);
                }
            }
        } finally {
            if (!tempTar.delete()) {
                tempTar.deleteOnExit();
            }
        }
    }

    private static void checkOk(ExtractOperationResult result) throws SevenZipException {
        if (result != ExtractOperationResult.OK) {
            throw new SevenZipException("Unwrapping the outer archive failed: " + result);
        }
    }

    /** The index of the first non-folder item - the inner archive in a single-stream wrapper. */
    private static int firstFileItem(IInArchive archive) throws SevenZipException {
        int count = archive.getNumberOfItems();
        for (int i = 0; i < count; i++) {
            if (!((Boolean) archive.getProperty(i, PropID.IS_FOLDER)).booleanValue()) {
                return i;
            }
        }
        throw new SevenZipException("Wrapper archive contains no file to unwrap");
    }

    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("Usage: java ExtractNestedArchive <wrapped-archive, e.g. foo.tar.gz>");
            return;
        }
        System.out.println("== In memory ==");
        printHeader();
        try {
            extractInMemory(args[0]);
        } catch (Exception e) {
            System.err.println("Error occurs: " + e);
        }

        System.out.println("== Via temporary file ==");
        printHeader();
        try {
            extractViaTempFile(args[0]);
        } catch (Exception e) {
            System.err.println("Error occurs: " + e);
        }
    }

    private static void printHeader() {
        System.out.println("   Hash   |    Size    | Filename");
        System.out.println("----------+------------+---------");
    }
}
Output
== In memory ==
   Hash   |    Size    | Filename
----------+------------+---------
 E606EF4B |         23 | hello.txt
 D444A5D4 |         10 | data/numbers.txt
 179C5D86 |         40 | data/readme.md
== Via temporary file ==
   Hash   |    Size    | Filename
----------+------------+---------
 E606EF4B |         23 | hello.txt
 D444A5D4 |         10 | data/numbers.txt
 179C5D86 |         40 | data/readme.md