Documentation

Code snippets

24 complete, runnable examples. Every snippet is a real program from the test suite — the shown output is verified on every release, on every platform. Use your browser's search (Ctrl+F) to find anything on this page.

These examples favour clarity, so error handling and stream lifecycle are kept minimal — that part is not the focus here and, in real code, must be done with care (close streams reliably, never swallow a failing close()). For the robust, production-grade treatment see the Extraction masterclass.

Getting started

#Verify native library initialization

Initializes 7-Zip-JBinding explicitly and prints the native library version — a minimal smoke test of your setup.

SevenZipJBindingInitCheck.java verified by SevenZipJBindingInitCheckTest
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipNativeInitializationException;

public class SevenZipJBindingInitCheck {
    public static void main(String[] args) {
        try {
            SevenZip.initSevenZipFromPlatformJAR();
            System.out.println("7-Zip-JBinding library was initialized");
        } catch (SevenZipNativeInitializationException e) {
            e.printStackTrace();
        }
    }
}
Output
7-Zip-JBinding library was initialized

Extraction

#List items (simple interface)

Iterate all items with the beginner-friendly simple interface: sizes, compressed sizes and paths.

ListItemsSimple.java verified by ListItemsSimpleTest
import java.io.IOException;
import java.io.RandomAccessFile;

import net.sf.sevenzipjbinding.IInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;

public class ListItemsSimple {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("Usage: java ListItemsSimple <archive-name>");
            return;
        }
        RandomAccessFile randomAccessFile = null;
        IInArchive inArchive = null;
        try {
            randomAccessFile = new RandomAccessFile(args[0], "r");
            inArchive = SevenZip.openInArchive(null, // autodetect archive type
                    new RandomAccessFileInStream(randomAccessFile));

            // Getting simple interface of the archive inArchive
            ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();

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

            for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
                System.out.println(String.format("%9s | %9s | %s", // 
                        item.getSize(), 
                        item.getPackedSize(), 
                        item.getPath()));
            }
        } catch (Exception e) {
            System.err.println("Error occurs: " + e);
        } finally {
            if (inArchive != null) {
                try {
                    inArchive.close();
                } catch (SevenZipException e) {
                    System.err.println("Error closing archive: " + e);
                }
            }
            if (randomAccessFile != null) {
                try {
                    randomAccessFile.close();
                } catch (IOException e) {
                    System.err.println("Error closing file: " + e);
                }
            }
        }
    }
}
Output
   Size   | Compr.Sz. | Filename
----------+-----------+---------
     4481 |        68 | file1.txt
       75 |        62 | file2.txt
        0 |         0 | folder
        6 |         6 | folder/file in folder.txt

#List items (standard interface)

The same listing through the full-power standard interface with typed property access.

ListItemsStandard.java verified by ListItemsStandardTest
import java.io.IOException;
import java.io.RandomAccessFile;

import net.sf.sevenzipjbinding.IInArchive;
import net.sf.sevenzipjbinding.PropID;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;

public class ListItemsStandard {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("Usage: java ListItemsStandard <archive-name>");
            return;
        }
        RandomAccessFile randomAccessFile = null;
        IInArchive inArchive = null;
        try {
            randomAccessFile = new RandomAccessFile(args[0], "r");
            inArchive = SevenZip.openInArchive(null, // autodetect archive type
                    new RandomAccessFileInStream(randomAccessFile));

            System.out.println("   Size   | Compr.Sz. | Filename");
            System.out.println("----------+-----------+---------");
            int itemCount = inArchive.getNumberOfItems();
            for (int i = 0; i < itemCount; i++) {
                System.out.println(String.format("%9s | %9s | %s", // 
                        inArchive.getProperty(i, PropID.SIZE), 
                        inArchive.getProperty(i, PropID.PACKED_SIZE), 
                        inArchive.getProperty(i, PropID.PATH)));
            }
        } catch (Exception e) {
            System.err.println("Error occurs: " + e);
        } finally {
            if (inArchive != null) {
                try {
                    inArchive.close();
                } catch (SevenZipException e) {
                    System.err.println("Error closing archive: " + e);
                }
            }
            if (randomAccessFile != null) {
                try {
                    randomAccessFile.close();
                } catch (IOException e) {
                    System.err.println("Error closing file: " + e);
                }
            }
        }
    }
}
Output
   Size   | Compr.Sz. | Filename
----------+-----------+---------
     4481 |        68 | file1.txt
       75 |        62 | file2.txt
        0 |         0 | folder
        6 |         6 | folder/file in folder.txt

#Extract items (simple interface)

Extract every item and consume the data through a callback — no temp files involved.

ExtractItemsSimple.java verified by ExtractItemsSimpleTest
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;

import net.sf.sevenzipjbinding.ExtractOperationResult;
import net.sf.sevenzipjbinding.IInArchive;
import net.sf.sevenzipjbinding.ISequentialOutStream;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;

public class ExtractItemsSimple {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("Usage: java ExtractItemsSimple <archive-name>");
            return;
        }
        RandomAccessFile randomAccessFile = null;
        IInArchive inArchive = null;
        try {
            randomAccessFile = new RandomAccessFile(args[0], "r");
            inArchive = SevenZip.openInArchive(null, // autodetect archive type
                    new RandomAccessFileInStream(randomAccessFile));

            // Getting simple interface of the archive inArchive
            ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();

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

            for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
                final int[] hash = new int[] { 0 };
                if (!item.isFolder()) {
                    ExtractOperationResult result;

                    final long[] sizeArray = new long[1];
                    result = item.extractSlow(new ISequentialOutStream() {
                        public int write(byte[] data) throws SevenZipException {
                            hash[0] ^= Arrays.hashCode(data); // Consume data
                            sizeArray[0] += data.length;
                            return data.length; // Return amount of consumed data
                        }
                    });

                    if (result == ExtractOperationResult.OK) {
                        System.out.println(String.format("%9X | %10s | %s", 
                                hash[0], sizeArray[0], item.getPath()));
                    } else {
                        System.err.println("Error extracting item: " + result);
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("Error occurs: " + e);
        } finally {
            if (inArchive != null) {
                try {
                    inArchive.close();
                } catch (SevenZipException e) {
                    System.err.println("Error closing archive: " + e);
                }
            }
            if (randomAccessFile != null) {
                try {
                    randomAccessFile.close();
                } catch (IOException e) {
                    System.err.println("Error closing file: " + e);
                }
            }
        }
    }
}
Output
   Hash   |    Size    | Filename
----------+------------+---------
 C1FD1029 |       4481 | file1.txt
 8CB12E6A |         75 | file2.txt
 E8EEC7F4 |          6 | folder/file in folder.txt

#Extract items (standard interface)

Sequential extraction with the standard interface for maximum control and speed.

ExtractItemsStandard.java verified by ExtractItemsStandardTest
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

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.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;

public class ExtractItemsStandard {
    public static class MyExtractCallback implements IArchiveExtractCallback {
        private int hash = 0;
        private int size = 0;
        private int index;
        private IInArchive inArchive;

        public MyExtractCallback(IInArchive inArchive) {
            this.inArchive = inArchive;
        }

        public ISequentialOutStream getStream(int index, 
                ExtractAskMode extractAskMode) throws SevenZipException {
            this.index = index;
            if (extractAskMode != ExtractAskMode.EXTRACT) {
                return null;
            }
            return new ISequentialOutStream() {

                public int write(byte[] data) throws SevenZipException {
                    hash ^= Arrays.hashCode(data);
                    size += data.length;
                    return data.length; // Return amount of proceed data
                }
            };
        }

        public void prepareOperation(ExtractAskMode extractAskMode) 
                throws SevenZipException {
        }

        public void setOperationResult(ExtractOperationResult 
                extractOperationResult) throws SevenZipException {
            if (extractOperationResult != ExtractOperationResult.OK) {
                System.err.println("Extraction error");
            } else {
                System.out.println(String.format("%9X | %10s | %s", hash, size,
                        inArchive.getProperty(index, PropID.PATH)));
                hash = 0;
                size = 0;
            }
        }

        public void setCompleted(long completeValue) throws SevenZipException {
        }

        public void setTotal(long total) throws SevenZipException {
        }

    }

    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("Usage: java ExtractItemsStandard <arch-name>");
            return;
        }
        RandomAccessFile randomAccessFile = null;
        IInArchive inArchive = null;
        try {
            randomAccessFile = new RandomAccessFile(args[0], "r");
            inArchive = SevenZip.openInArchive(null, // autodetect archive type
                    new RandomAccessFileInStream(randomAccessFile));

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

            int count = inArchive.getNumberOfItems();
            List<Integer> itemsToExtract = new ArrayList<Integer>();
            for (int i = 0; i < count; i++) {
                if (!((Boolean) inArchive.getProperty(i, PropID.IS_FOLDER))
                        .booleanValue()) {
                    itemsToExtract.add(Integer.valueOf(i));
                }
            }
            int[] items = new int[itemsToExtract.size()];
            int i = 0;
            for (Integer integer : itemsToExtract) {
                items[i++] = integer.intValue();
            }
            inArchive.extract(items, false, // Non-test mode
                    new MyExtractCallback(inArchive));
        } catch (Exception e) {
            System.err.println("Error occurs: " + e);
        } finally {
            if (inArchive != null) {
                try {
                    inArchive.close();
                } catch (SevenZipException e) {
                    System.err.println("Error closing archive: " + e);
                }
            }
            if (randomAccessFile != null) {
                try {
                    randomAccessFile.close();
                } catch (IOException e) {
                    System.err.println("Error closing file: " + e);
                }
            }
        }
    }
}
Output
   Hash   |    Size    | Filename
----------+------------+---------
 C1FD1029 |       4481 | file1.txt
 8CB12E6A |         75 | file2.txt
 E8EEC7F4 |          6 | folder/file in folder.txt

#Extract items (standard interface, callback)

The standard extraction driven entirely by your IArchiveExtractCallback — full control over data sinks and progress.

ExtractItemsStandardCallback.java verified by ExtractItemsStandardCallbackTest
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.ISequentialOutStream;
import net.sf.sevenzipjbinding.PropID;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;

public class ExtractItemsStandardCallback {
    public static class MyExtractCallback implements IArchiveExtractCallback {
        private int hash = 0;
        private int size = 0;
        private int index;
        private boolean skipExtraction;
        private IInArchive inArchive;

        public MyExtractCallback(IInArchive inArchive) {
            this.inArchive = inArchive;
        }

        public ISequentialOutStream getStream(int index, 
                ExtractAskMode extractAskMode) throws SevenZipException {
            this.index = index;
            skipExtraction = (Boolean) inArchive
                    .getProperty(index, PropID.IS_FOLDER);
            if (skipExtraction || extractAskMode != ExtractAskMode.EXTRACT) {
                return null;
            }
            return new ISequentialOutStream() {
                public int write(byte[] data) throws SevenZipException {
                    hash ^= Arrays.hashCode(data);
                    size += data.length;
                    return data.length; // Return amount of proceed data
                }
            };
        }

        public void prepareOperation(ExtractAskMode extractAskMode) 
                throws SevenZipException {
        }

        public void setOperationResult(ExtractOperationResult 
                extractOperationResult) throws SevenZipException {
            if (skipExtraction) {
                return;
            }
            if (extractOperationResult != ExtractOperationResult.OK) {
                System.err.println("Extraction error");
            } else {
                System.out.println(String.format("%9X | %10s | %s", hash, size,// 
                        inArchive.getProperty(index, PropID.PATH)));
                hash = 0;
                size = 0;
            }
        }

        public void setCompleted(long completeValue) throws SevenZipException {
        }

        public void setTotal(long total) throws SevenZipException {
        }
    }

    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("Usage: java ExtractItemsStandard <arch-name>");
            return;
        }
        RandomAccessFile randomAccessFile = null;
        IInArchive inArchive = null;
        try {
            randomAccessFile = new RandomAccessFile(args[0], "r");
            inArchive = SevenZip.openInArchive(null, // autodetect archive type
                    new RandomAccessFileInStream(randomAccessFile));

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

            int[] in = new int[inArchive.getNumberOfItems()];
            for (int i = 0; i < in.length; i++) {
                in[i] = i;
            }
            inArchive.extract(in, false, // Non-test mode
                    new MyExtractCallback(inArchive));
        } catch (Exception e) {
            System.err.println("Error occurs: " + e);
        } finally {
            if (inArchive != null) {
                try {
                    inArchive.close();
                } catch (SevenZipException e) {
                    System.err.println("Error closing archive: " + e);
                }
            }
            if (randomAccessFile != null) {
                try {
                    randomAccessFile.close();
                } catch (IOException e) {
                    System.err.println("Error closing file: " + e);
                }
            }
        }
    }
}
Output
   Hash   |    Size    | Filename
----------+------------+---------
 C1FD1029 |       4481 | file1.txt
 8CB12E6A |         75 | file2.txt
 E8EEC7F4 |          6 | folder/file in folder.txt

#Extract a whole archive to disk (fast &amp; correct)

The recommended way to unpack an entire archive to a directory: a single extract() call that stays O(n) even on solid 7z. The Extraction masterclass explains every rule behind it.

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

#Extract a wrapped archive (tar.gz) in one go

Unwrap an archive nested inside another (e.g. .tar.gz = a .tar inside a GZip) in two open/extract steps — shown both fully in memory (ByteArrayStream, no temp file) and via a temporary file for huge inner archives.

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

#Open multi-part 7z archives (7z.001, …)

Combine volume files transparently with IArchiveOpenVolumeCallback.

OpenMultipartArchive7z.java verified by OpenMultipartArchive7zTest
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.Map;

import net.sf.sevenzipjbinding.ArchiveFormat;
import net.sf.sevenzipjbinding.IArchiveOpenVolumeCallback;
import net.sf.sevenzipjbinding.IInArchive;
import net.sf.sevenzipjbinding.IInStream;
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.VolumedArchiveInStream;

public class OpenMultipartArchive7z {
    /**
     * In this example we use VolumedArchiveInStream class only.
     * It means, we doesn't pass instances of this class directly
     * to 7-Zip, so not complete implementation
     * of {@link IArchiveOpenVolumeCallback} is required.
     * See VolumedArchiveInStream JavaDoc for more information
     */
    private static class ArchiveOpenVolumeCallback 
            implements IArchiveOpenVolumeCallback {

        /**
         * Cache for opened file streams
         */
        private Map<String, RandomAccessFile> openedRandomAccessFileList = 
                        new HashMap<String, RandomAccessFile>();

        /**
         * This method doesn't needed, if using with VolumedArchiveInStream
         * and pass the name of the first archive in constructor.
         * (Use two argument constructor)
         * 
         * @see IArchiveOpenVolumeCallback#getProperty(PropID)
         */
        public Object getProperty(PropID propID) throws SevenZipException {
            return null;
        }

        /**
         * 
         * The name of the required volume will be calculated out of the
         * name of the first volume and volume index. If you need
         * need volume index (integer) you will have to parse filename
         * and extract index.
         * 
         * <pre>
         * int index = filename.substring(filename.length() - 3, 
         *         filename.length());
         * </pre>
         * 
         */
        public IInStream getStream(String filename) throws SevenZipException {
            try {
                // We use caching of opened streams, so check cache first
                RandomAccessFile randomAccessFile = openedRandomAccessFileList
                        .get(filename);
                if (randomAccessFile != null) { // Cache hit.
                    // Move the file pointer back to the beginning
                    // in order to emulating new stream
                    randomAccessFile.seek(0);
                    return new RandomAccessFileInStream(randomAccessFile);
                }

                // Nothing useful in cache. Open required volume.
                randomAccessFile = new RandomAccessFile(filename, "r");

                // Put new stream in the cache
                openedRandomAccessFileList.put(filename, randomAccessFile);

                return new RandomAccessFileInStream(randomAccessFile);
            } catch (FileNotFoundException fileNotFoundException) {
                // Required volume doesn't exist. This happens if the volume:
                // 1. never exists. 7-Zip doesn't know how many volumes should
                //    exist, so it have to try each volume.
                // 2. should be there, but doesn't. This is an error case.

                // Since normal and error cases are possible,
                // we can't throw an error message
                return null; // We return always null in this case
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        /**
         * Close all opened streams
         */
        void close() throws IOException {
            for (RandomAccessFile file : openedRandomAccessFileList.values()) {
                file.close();
            }
        }
    }

    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println(
                    "Usage: java OpenMultipartArchive7z <first-volume>");
            return;
        }
        ArchiveOpenVolumeCallback archiveOpenVolumeCallback = null;
        IInArchive inArchive = null;
        try {

            archiveOpenVolumeCallback = new ArchiveOpenVolumeCallback();
            inArchive = SevenZip.openInArchive(ArchiveFormat.SEVEN_ZIP, 
                    new VolumedArchiveInStream(args[0], 
                            archiveOpenVolumeCallback));

            System.out.println("   Size   | Compr.Sz. | Filename");
            System.out.println("----------+-----------+---------");
            int itemCount = inArchive.getNumberOfItems();
            for (int i = 0; i < itemCount; i++) {
                System.out.println(String.format("%9s | %9s | %s", // 
                        inArchive.getProperty(i, PropID.SIZE), 
                        inArchive.getProperty(i, PropID.PACKED_SIZE), 
                        inArchive.getProperty(i, PropID.PATH)));
            }
        } catch (Exception e) {
            System.err.println("Error occurs: " + e);
        } finally {
            if (inArchive != null) {
                try {
                    inArchive.close();
                } catch (SevenZipException e) {
                    System.err.println("Error closing archive: " + e);
                }
            }
            if (archiveOpenVolumeCallback != null) {
                try {
                    archiveOpenVolumeCallback.close();
                } catch (IOException e) {
                    System.err.println("Error closing file: " + e);
                }
            }
        }
    }
}
Output
   Size   | Compr.Sz. | Filename
----------+-----------+---------
        6 |       114 | folder/file in folder.txt
     4481 |      null | file1.txt
       75 |      null | file2.txt
        0 |         0 | folder

#Open multi-part RAR archives (.part1.rar, …)

RAR volumes use their own naming scheme; this callback resolves them.

OpenMultipartArchiveRar.java verified by OpenMultipartArchiveRarTest
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.Map;

import net.sf.sevenzipjbinding.ArchiveFormat;
import net.sf.sevenzipjbinding.IArchiveOpenCallback;
import net.sf.sevenzipjbinding.IArchiveOpenVolumeCallback;
import net.sf.sevenzipjbinding.IInArchive;
import net.sf.sevenzipjbinding.IInStream;
import net.sf.sevenzipjbinding.PropID;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;

public class OpenMultipartArchiveRar {
    private static class ArchiveOpenVolumeCallback 
            implements IArchiveOpenVolumeCallback, IArchiveOpenCallback {

        /**
         * Cache for opened file streams
         */
        private Map<String, RandomAccessFile> openedRandomAccessFileList = 
                        new HashMap<String, RandomAccessFile>();

        /**
         * Name of the last volume returned by {@link #getStream(String)}
         */
        private String name ;

        /**
         * This method should at least provide the name of the last
         * opened volume (propID=PropID.NAME).
         * 
         * @see IArchiveOpenVolumeCallback#getProperty(PropID)
         */
        public Object getProperty(PropID propID) throws SevenZipException {
            switch (propID) {
            case NAME:
                return name ;
            }
            return null;
        }

        /**
         * The name of the required volume will be calculated out of the
         * name of the first volume and a volume index. In case of RAR file,
         * the substring ".partNN." in the name of the volume file will
         * indicate a volume with id NN. For example:
         * <ul>
         * <li>test.rar - single part archive or multi-part archive with
         * a single volume</li>
         * <li>test.part23.rar - 23-th part of a multi-part archive</li>
         * <li>test.part001.rar - first part of a multi-part archive.
         * "00" indicates, that at least 100 volumes must exist.</li>
         * </ul>
         */
        public IInStream getStream(String filename) throws SevenZipException {
            try {
                // We use caching of opened streams, so check cache first
                RandomAccessFile randomAccessFile = openedRandomAccessFileList
                        .get(filename);
                if (randomAccessFile != null) { // Cache hit.
                    // Move the file pointer back to the beginning
                    // in order to emulating new stream
                    randomAccessFile.seek(0);

                    // Save current volume name in case getProperty() will be called
                    name = filename;

                    return new RandomAccessFileInStream(randomAccessFile);
                }

                // Nothing useful in cache. Open required volume.
                randomAccessFile = new RandomAccessFile(filename, "r");

                // Put new stream in the cache
                openedRandomAccessFileList.put(filename, randomAccessFile);

                // Save current volume name in case getProperty() will be called
                name = filename;
                return new RandomAccessFileInStream(randomAccessFile);
            } catch (FileNotFoundException fileNotFoundException) {
                // Required volume doesn't exist. This happens if the volume:
                // 1. never exists. 7-Zip doesn't know how many volumes should
                //    exist, so it have to try each volume.
                // 2. should be there, but doesn't. This is an error case.

                // Since normal and error cases are possible,
                // we can't throw an error message
                return null; // We return always null in this case
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        /**
         * Close all opened streams
         */
        void close() throws IOException {
            for (RandomAccessFile file : openedRandomAccessFileList.values()) {
                file.close();
            }
        }

        public void setCompleted(Long files, Long bytes) throws SevenZipException {
        }

        public void setTotal(Long files, Long bytes) throws SevenZipException {
        }
    }

    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println(
                    "Usage: java OpenMultipartArchiveRar <first-volume>");
            return;
        }
        ArchiveOpenVolumeCallback archiveOpenVolumeCallback = null;
        IInArchive inArchive = null;
        try {

            archiveOpenVolumeCallback = new ArchiveOpenVolumeCallback();
            IInStream inStream = archiveOpenVolumeCallback.getStream(args[0]);
            inArchive = SevenZip.openInArchive(ArchiveFormat.RAR, inStream, 
                    archiveOpenVolumeCallback);

            System.out.println("   Size   | Compr.Sz. | Filename");
            System.out.println("----------+-----------+---------");
            int itemCount = inArchive.getNumberOfItems();
            for (int i = 0; i < itemCount; i++) {
                System.out.println(String.format("%9s | %9s | %s", 
                        inArchive.getProperty(i, PropID.SIZE), 
                        inArchive.getProperty(i, PropID.PACKED_SIZE), 
                        inArchive.getProperty(i, PropID.PATH)));
            }
        } catch (Exception e) {
            System.err.println("Error occurs: " + e);
        } finally {
            if (inArchive != null) {
                try {
                    inArchive.close();
                } catch (SevenZipException e) {
                    System.err.println("Error closing archive: " + e);
                }
            }
            if (archiveOpenVolumeCallback != null) {
                try {
                    archiveOpenVolumeCallback.close();
                } catch (IOException e) {
                    System.err.println("Error closing file: " + e);
                }
            }
        }
    }
}
Output
   Size   | Compr.Sz. | Filename
----------+-----------+---------
        6 |         6 | folder/file in folder.txt
     4481 |      4481 | file1.txt
       75 |        75 | file2.txt
        0 |         0 | folder

Compression

#The archive structure used in these examples

A small in-memory file tree shared by all compression snippets below.

CompressArchiveStructure.java verified by CompressArchiveStructureTest
public class CompressArchiveStructure {
    public static Item[] create() {

        //     <root>
        //     |
        //     +- info.txt
        //     +- random-100-bytes.dump
        //     +- dir1
        //     |  +- file-in-a-directory1.txt
        //     +- dir2
        //        +- file-in-a-directory2.txt

        Item[] items = new Item[5];

        items[0] = new Item("info.txt", "This is the info");

        byte[] content = new byte[100];
        new Random().nextBytes(content);
        items[1] = new Item("random-100-bytes.dump", content);

        // dir1 doesn't have separate archive item
        items[2] = new Item("dir1" + File.separator + "file1.txt", 
                "This file located in a directory 'dir'");

        // dir2 does have separate archive item
        items[3] = new Item("dir2" + File.separator, (byte[]) null);
        items[4] = new Item("dir2" + File.separator + "file2.txt", 
                "This file located in a directory 'dir'");
        return items;
    }

    static class Item {
        private String path;
        private byte[] content;

        Item(String path, String content) {
            this(path, content.getBytes());
        }

        Item(String path, byte[] content) {
            this.path= path;
            this.content= content;
        }

        String getPath() {
            return path;
        }

        byte[] getContent() {
            return content;
        }
    }
}

#Create archives (generic API, all formats)

One code path that can write 7z, Zip, Tar, GZip, BZip2 — the format is a runtime parameter.

CompressGeneric.java verified by CompressGenericTest
import java.io.IOException;
import java.io.RandomAccessFile;

import net.sf.sevenzipjbinding.ArchiveFormat;
import net.sf.sevenzipjbinding.IOutCreateArchive;
import net.sf.sevenzipjbinding.IOutCreateCallback;
import net.sf.sevenzipjbinding.IOutFeatureSetLevel;
import net.sf.sevenzipjbinding.IOutFeatureSetMultithreading;
import net.sf.sevenzipjbinding.IOutItemAllFormats;
import net.sf.sevenzipjbinding.ISequentialInStream;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.OutItemFactory;
import net.sf.sevenzipjbinding.impl.RandomAccessFileOutStream;
import net.sf.sevenzipjbinding.junit.snippets.CompressArchiveStructure.Item;
import net.sf.sevenzipjbinding.util.ByteArrayStream;

public class CompressGeneric {
    /**
     * The callback provides information about archive items.
     */
    private final class MyCreateCallback 
            implements IOutCreateCallback<IOutItemAllFormats> {

        public void setOperationResult(boolean operationResultOk)
                throws SevenZipException {
            // Track each operation result here
        }

        public void setTotal(long total) throws SevenZipException {
            // Track operation progress here
        }

        public void setCompleted(long complete) throws SevenZipException {
            // Track operation progress here
        }

        public IOutItemAllFormats getItemInformation(int index,
                OutItemFactory<IOutItemAllFormats> outItemFactory) {
            IOutItemAllFormats item = outItemFactory.createOutItem();

            if (items[index].getContent() == null) {
                // Directory
                item.setPropertyIsDir(true);
            } else {
                // File
                item.setDataSize((long) items[index].getContent().length);
            }

            item.setPropertyPath(items[index].getPath());

            return item;
        }

        public ISequentialInStream getStream(int i) throws SevenZipException {
            if (items[i].getContent() == null) {
                return null;
            }
            return new ByteArrayStream(items[i].getContent(), true);
        }
    }

    private Item[] items;

    public static void main(String[] args) {
        if (args.length != 3) {
            System.out.println("Usage: java CompressGeneric " 
                    + "<archive-format> <archive> <count-of-files>");
            for (ArchiveFormat af : ArchiveFormat.values()) {
                if (af.isOutArchiveSupported()) {
                    System.out.println("Supported formats: " + af.name());
                }
            }
            return;
        }

        int itemsCount = Integer.valueOf(args[2]);
        new CompressGeneric().compress(args[0], args[1], itemsCount);
    }


    private void compress(String filename, String fmtName, int count) {
        items = CompressArchiveStructure.create();

        boolean success = false;
        RandomAccessFile raf = null;
        IOutCreateArchive<IOutItemAllFormats> outArchive = null;
        ArchiveFormat archiveFormat = ArchiveFormat.valueOf(fmtName);
        try {
            raf = new RandomAccessFile(filename, "rw");

            // Open out-archive object
            outArchive = SevenZip.openOutArchive(archiveFormat);

            // Configure archive
            if (outArchive instanceof IOutFeatureSetLevel) {
                ((IOutFeatureSetLevel) outArchive).setLevel(5);
            }
            if (outArchive instanceof IOutFeatureSetMultithreading) {
                ((IOutFeatureSetMultithreading) outArchive).setThreadCount(2);
            }

            // Create archive
            outArchive.createArchive(new RandomAccessFileOutStream(raf),
                    count, new MyCreateCallback());

            success = true;
        } catch (SevenZipException e) {
            System.err.println("7z-Error occurs:");
            // Get more information using extended method
            e.printStackTraceExtended();
        } catch (Exception e) {
            System.err.println("Error occurs: " + e);
        } finally {
            if (outArchive != null) {
                try {
                    outArchive.close();
                } catch (IOException e) {
                    System.err.println("Error closing archive: " + e);
                    success = false;
                }
            }
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    System.err.println("Error closing file: " + e);
                    success = false;
                }
            }
        }
        if (success) {
            System.out.println(archiveFormat.getMethodName() 
                    + " archive with " + count + " item(s) created");
        }
    }
}
Output
Zip archive with 5 item(s) created

#Create a 7z archive (format-specific API)

The 7z-specific interface exposes format features like solid blocks and header encryption.

CompressNonGeneric7z.java verified by CompressNonGeneric7zTest
import java.io.IOException;
import java.io.RandomAccessFile;

import net.sf.sevenzipjbinding.IOutCreateArchive7z;
import net.sf.sevenzipjbinding.IOutCreateCallback;
import net.sf.sevenzipjbinding.IOutItem7z;
import net.sf.sevenzipjbinding.ISequentialInStream;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.OutItemFactory;
import net.sf.sevenzipjbinding.impl.RandomAccessFileOutStream;
import net.sf.sevenzipjbinding.junit.snippets.CompressArchiveStructure.Item;
import net.sf.sevenzipjbinding.util.ByteArrayStream;

public class CompressNonGeneric7z {
    /**
     * The callback provides information about archive items.
     */
    private final class MyCreateCallback 
            implements IOutCreateCallback<IOutItem7z> {

        public void setOperationResult(boolean operationResultOk)
                throws SevenZipException {
            // Track each operation result here
        }

        public void setTotal(long total) throws SevenZipException {
            // Track operation progress here
        }

        public void setCompleted(long complete) throws SevenZipException {
            // Track operation progress here
        }

        public IOutItem7z getItemInformation(int index,
                OutItemFactory<IOutItem7z> outItemFactory) {
            IOutItem7z item = outItemFactory.createOutItem();

            if (items[index].getContent() == null) {
                // Directory
                item.setPropertyIsDir(true);
            } else {
                // File
                item.setDataSize((long) items[index].getContent().length);
            }

            item.setPropertyPath(items[index].getPath());

            return item;
        }

        public ISequentialInStream getStream(int i) throws SevenZipException {
            if (items[i].getContent() == null) {
                return null;
            }
            return new ByteArrayStream(items[i].getContent(), true);
        }
    }

    private Item[] items;

    public static void main(String[] args) {
        if (args.length == 1) {
            new CompressNonGeneric7z().compress(args[0]);
            return;
        }
        System.out.println("Usage: java CompressNonGeneric7z <archive>");
    }


    private void compress(String filename) {
        items = CompressArchiveStructure.create();

        boolean success = false;
        RandomAccessFile raf = null;
        IOutCreateArchive7z outArchive = null;
        try {
            raf = new RandomAccessFile(filename, "rw");

            // Open out-archive object
            outArchive = SevenZip.openOutArchive7z();

            // Configure archive
            outArchive.setLevel(5);
            outArchive.setSolid(true);

            // Create archive
            outArchive.createArchive(new RandomAccessFileOutStream(raf),
                    items.length, new MyCreateCallback());

            success = true;
        } catch (SevenZipException e) {
            System.err.println("7z-Error occurs:");
            // Get more information using extended method
            e.printStackTraceExtended();
        } catch (Exception e) {
            System.err.println("Error occurs: " + e);
        } finally {
            if (outArchive != null) {
                try {
                    outArchive.close();
                } catch (IOException e) {
                    System.err.println("Error closing archive: " + e);
                    success = false;
                }
            }
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    System.err.println("Error closing file: " + e);
                    success = false;
                }
            }
        }
        if (success) {
            System.out.println("Compression operation succeeded");
        }
    }
}
Output
Compression operation succeeded

#Create a Zip archive

Zip-specific archive creation with per-item attributes.

CompressNonGenericZip.java verified by CompressNonGenericZipTest
import java.io.IOException;
import java.io.RandomAccessFile;

import net.sf.sevenzipjbinding.IOutCreateArchiveZip;
import net.sf.sevenzipjbinding.IOutCreateCallback;
import net.sf.sevenzipjbinding.IOutItemZip;
import net.sf.sevenzipjbinding.ISequentialInStream;
import net.sf.sevenzipjbinding.PropID;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.OutItemFactory;
import net.sf.sevenzipjbinding.impl.RandomAccessFileOutStream;
import net.sf.sevenzipjbinding.junit.snippets.CompressArchiveStructure.Item;
import net.sf.sevenzipjbinding.util.ByteArrayStream;

public class CompressNonGenericZip {
    /**
     * The callback provides information about archive items.
     */
    private final class MyCreateCallback 
            implements IOutCreateCallback<IOutItemZip> {

        public void setOperationResult(boolean operationResultOk)
                throws SevenZipException {
            // Track each operation result here
        }

        public void setTotal(long total) throws SevenZipException {
            // Track operation progress here
        }

        public void setCompleted(long complete) throws SevenZipException {
            // Track operation progress here
        }

        public IOutItemZip getItemInformation(int index,
                OutItemFactory<IOutItemZip> outItemFactory) {
            int attr = PropID.AttributesBitMask.FILE_ATTRIBUTE_UNIX_EXTENSION;

            IOutItemZip item = outItemFactory.createOutItem();

            if (items[index].getContent() == null) {
                // Directory
                item.setPropertyIsDir(true);
                attr |= PropID.AttributesBitMask.FILE_ATTRIBUTE_DIRECTORY;
                attr |= 0x81ED << 16; // permissions: drwxr-xr-x
            } else {
                // File
                item.setDataSize((long) items[index].getContent().length);
                attr |= 0x81a4 << 16; // permissions: -rw-r--r--
            }
            item.setPropertyPath(items[index].getPath());

            item.setPropertyAttributes(attr);

            return item;
        }

        public ISequentialInStream getStream(int i) throws SevenZipException {
            if (items[i].getContent() == null) {
                return null;
            }
            return new ByteArrayStream(items[i].getContent(), true);
        }
    }

    private Item[] items;

    public static void main(String[] args) {
        if (args.length == 1) {
            new CompressNonGenericZip().compress(args[0]);
            return;
        }
        System.out.println("Usage: java CompressNonGenericZip <archive>");
    }


    private void compress(String filename) {
        items = CompressArchiveStructure.create();

        boolean success = false;
        RandomAccessFile raf = null;
        IOutCreateArchiveZip outArchive = null;
        try {
            raf = new RandomAccessFile(filename, "rw");

            // Open out-archive object
            outArchive = SevenZip.openOutArchiveZip();

            // Configure archive
            outArchive.setLevel(5);

            // Create archive
            outArchive.createArchive(new RandomAccessFileOutStream(raf),
                    items.length, new MyCreateCallback());

            success = true;
        } catch (SevenZipException e) {
            System.err.println("7z-Error occurs:");
            // Get more information using extended method
            e.printStackTraceExtended();
        } catch (Exception e) {
            System.err.println("Error occurs: " + e);
        } finally {
            if (outArchive != null) {
                try {
                    outArchive.close();
                } catch (IOException e) {
                    System.err.println("Error closing archive: " + e);
                    success = false;
                }
            }
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    System.err.println("Error closing file: " + e);
                    success = false;
                }
            }
        }
        if (success) {
            System.out.println("Compression operation succeeded");
        }
    }
}
Output
Compression operation succeeded

#Create a Tar archive

Tar with POSIX attributes — user, group and permissions.

CompressNonGenericTar.java verified by CompressNonGenericTarTest
import java.io.IOException;
import java.io.RandomAccessFile;

import net.sf.sevenzipjbinding.IOutCreateArchiveTar;
import net.sf.sevenzipjbinding.IOutCreateCallback;
import net.sf.sevenzipjbinding.IOutItemTar;
import net.sf.sevenzipjbinding.ISequentialInStream;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.OutItemFactory;
import net.sf.sevenzipjbinding.impl.RandomAccessFileOutStream;
import net.sf.sevenzipjbinding.junit.snippets.CompressArchiveStructure.Item;
import net.sf.sevenzipjbinding.util.ByteArrayStream;

public class CompressNonGenericTar {
    /**
     * The callback provides information about archive items.
     */
    private final class MyCreateCallback 
            implements IOutCreateCallback<IOutItemTar> {

        public void setOperationResult(boolean operationResultOk)
                throws SevenZipException {
            // Track each operation result here
        }

        public void setTotal(long total) throws SevenZipException {
            // Track operation progress here
        }

        public void setCompleted(long complete) throws SevenZipException {
            // Track operation progress here
        }

        public IOutItemTar getItemInformation(int index,
                OutItemFactory<IOutItemTar> outItemFactory) {
            IOutItemTar item = outItemFactory.createOutItem();

            if (items[index].getContent() == null) {
                // Directory
                item.setPropertyIsDir(true);
            } else {
                // File
                item.setDataSize((long) items[index].getContent().length);
            }

            item.setPropertyPath(items[index].getPath());

            return item;
        }

        public ISequentialInStream getStream(int i) throws SevenZipException {
            if (items[i].getContent() == null) {
                return null;
            }
            return new ByteArrayStream(items[i].getContent(), true);
        }
    }

    private Item[] items;

    public static void main(String[] args) {
        if (args.length == 1) {
            new CompressNonGenericTar().compress(args[0]);
            return;
        }
        System.out.println("Usage: java CompressNonGenericTar <archive>");
    }


    private void compress(String filename) {
        items = CompressArchiveStructure.create();

        boolean success = false;
        RandomAccessFile raf = null;
        IOutCreateArchiveTar outArchive = null;
        try {
            raf = new RandomAccessFile(filename, "rw");

            // Open out-archive object
            outArchive = SevenZip.openOutArchiveTar();

            // No configuration methods for Tar

            // Create archive
            outArchive.createArchive(new RandomAccessFileOutStream(raf),
                    items.length, new MyCreateCallback());

            success = true;
        } catch (SevenZipException e) {
            System.err.println("Tar-Error occurs:");
            // Get more information using extended method
            e.printStackTraceExtended();
        } catch (Exception e) {
            System.err.println("Error occurs: " + e);
        } finally {
            if (outArchive != null) {
                try {
                    outArchive.close();
                } catch (IOException e) {
                    System.err.println("Error closing archive: " + e);
                    success = false;
                }
            }
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    System.err.println("Error closing file: " + e);
                    success = false;
                }
            }
        }
        if (success) {
            System.out.println("Compression operation succeeded");
        }
    }
}
Output
Compression operation succeeded

#Create a GZip archive (single stream)

Stream formats compress exactly one item.

CompressNonGenericGZip.java verified by CompressNonGenericGZipTest
import java.io.IOException;
import java.io.RandomAccessFile;

import net.sf.sevenzipjbinding.IOutCreateArchiveGZip;
import net.sf.sevenzipjbinding.IOutCreateCallback;
import net.sf.sevenzipjbinding.IOutItemGZip;
import net.sf.sevenzipjbinding.ISequentialInStream;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.OutItemFactory;
import net.sf.sevenzipjbinding.impl.RandomAccessFileOutStream;
import net.sf.sevenzipjbinding.util.ByteArrayStream;

public class CompressNonGenericGZip {
    /**
     * The callback provides information about archive items.
     */
    private final class MyCreateCallback 
            implements IOutCreateCallback<IOutItemGZip> {

        public void setOperationResult(boolean operationResultOk)
                throws SevenZipException {
            // Track each operation result here
        }

        public void setTotal(long total) throws SevenZipException {
            // Track operation progress here
        }

        public void setCompleted(long complete) throws SevenZipException {
            // Track operation progress here
        }

        public IOutItemGZip getItemInformation(int index,
                OutItemFactory<IOutItemGZip> outItemFactory) {
            IOutItemGZip item = outItemFactory.createOutItem();

            item.setDataSize((long) content.length);

            return item;
        }

        public ISequentialInStream getStream(int i) throws SevenZipException {
            return new ByteArrayStream(content, true);
        }
    }

    byte[] content;

    public static void main(String[] args) {
        if (args.length == 1) {
            new CompressNonGenericGZip().compress(args[0]);
            return;
        }
        System.out.println("Usage: java CompressNonGenericGZip <archive>");
    }

    private void compress(String filename) {
        boolean success = false;
        RandomAccessFile raf = null;
        IOutCreateArchiveGZip outArchive = null;
        content = CompressArchiveStructure.create()[0].getContent();
        try {
            raf = new RandomAccessFile(filename, "rw");

            // Open out-archive object
            outArchive = SevenZip.openOutArchiveGZip();

            // Configure archive
            outArchive.setLevel(5);

            // Create archive
            outArchive.createArchive(new RandomAccessFileOutStream(raf),
                    1, new MyCreateCallback());

            success = true;
        } catch (SevenZipException e) {
            System.err.println("GZip-Error occurs:");
            // Get more information using extended method
            e.printStackTraceExtended();
        } catch (Exception e) {
            System.err.println("Error occurs: " + e);
        } finally {
            if (outArchive != null) {
                try {
                    outArchive.close();
                } catch (IOException e) {
                    System.err.println("Error closing archive: " + e);
                    success = false;
                }
            }
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    System.err.println("Error closing file: " + e);
                    success = false;
                }
            }
        }
        if (success) {
            System.out.println("Compression operation succeeded");
        }
    }
}
Output
Compression operation succeeded

#Create a BZip2 archive (single stream)

Same single-stream model as GZip, different codec.

CompressNonGenericBZip2.java verified by CompressNonGenericBZip2Test
import java.io.IOException;
import java.io.RandomAccessFile;

import net.sf.sevenzipjbinding.IOutCreateArchiveBZip2;
import net.sf.sevenzipjbinding.IOutCreateCallback;
import net.sf.sevenzipjbinding.IOutItemBZip2;
import net.sf.sevenzipjbinding.ISequentialInStream;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.OutItemFactory;
import net.sf.sevenzipjbinding.impl.RandomAccessFileOutStream;
import net.sf.sevenzipjbinding.util.ByteArrayStream;

public class CompressNonGenericBZip2 {
    /**
     * The callback provides information about archive items.
     */
    private final class MyCreateCallback 
            implements IOutCreateCallback<IOutItemBZip2> {

        public void setOperationResult(boolean operationResultOk)
                throws SevenZipException {
            // Track each operation result here
        }

        public void setTotal(long total) throws SevenZipException {
            // Track operation progress here
        }

        public void setCompleted(long complete) throws SevenZipException {
            // Track operation progress here
        }

        public IOutItemBZip2 getItemInformation(int index,
                OutItemFactory<IOutItemBZip2> outItemFactory) {
            IOutItemBZip2 item = outItemFactory.createOutItem();

            item.setDataSize((long) content.length);

            return item;
        }

        public ISequentialInStream getStream(int i) throws SevenZipException {
            return new ByteArrayStream(content, true);
        }
    }

    byte[] content;

    public static void main(String[] args) {
        if (args.length == 1) {
            new CompressNonGenericBZip2().compress(args[0]);
            return;
        }
        System.out.println("Usage: java CompressNonGenericBZip2 <archive>");
    }

    private void compress(String filename) {
        boolean success = false;
        RandomAccessFile raf = null;
        IOutCreateArchiveBZip2 outArchive = null;
        content = CompressArchiveStructure.create()[0].getContent();
        try {
            raf = new RandomAccessFile(filename, "rw");

            // Open out-archive object
            outArchive = SevenZip.openOutArchiveBZip2();

            // Configure archive
            outArchive.setLevel(5);

            // Create archive
            outArchive.createArchive(new RandomAccessFileOutStream(raf),
                    1, new MyCreateCallback());

            success = true;
        } catch (SevenZipException e) {
            System.err.println("BZip2-Error occurs:");
            // Get more information using extended method
            e.printStackTraceExtended();
        } catch (Exception e) {
            System.err.println("Error occurs: " + e);
        } finally {
            if (outArchive != null) {
                try {
                    outArchive.close();
                } catch (IOException e) {
                    System.err.println("Error closing archive: " + e);
                    success = false;
                }
            }
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    System.err.println("Error closing file: " + e);
                    success = false;
                }
            }
        }
        if (success) {
            System.out.println("Compression operation succeeded");
        }
    }
}
Output
Compression operation succeeded

#Create an XZ archive (single stream) — new in 23.01

XZ compression support is new in 23.01-2.2.

CompressNonGenericXz.java verified by CompressNonGenericXzTest
import java.io.IOException;
import java.io.RandomAccessFile;

import net.sf.sevenzipjbinding.IOutCreateArchiveXz;
import net.sf.sevenzipjbinding.IOutCreateCallback;
import net.sf.sevenzipjbinding.IOutItemXz;
import net.sf.sevenzipjbinding.ISequentialInStream;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.OutItemFactory;
import net.sf.sevenzipjbinding.impl.RandomAccessFileOutStream;
import net.sf.sevenzipjbinding.util.ByteArrayStream;

public class CompressNonGenericXz {
    /**
     * The callback provides information about archive items.
     */
    private final class MyCreateCallback 
            implements IOutCreateCallback<IOutItemXz> {

        public void setOperationResult(boolean operationResultOk)
                throws SevenZipException {
            // Track each operation result here
        }

        public void setTotal(long total) throws SevenZipException {
            // Track operation progress here
        }

        public void setCompleted(long complete) throws SevenZipException {
            // Track operation progress here
        }

        public IOutItemXz getItemInformation(int index,
                OutItemFactory<IOutItemXz> outItemFactory) {
            IOutItemXz item = outItemFactory.createOutItem();

            item.setDataSize((long) content.length);

            return item;
        }

        public ISequentialInStream getStream(int i) throws SevenZipException {
            return new ByteArrayStream(content, true);
        }
    }

    byte[] content;

    public static void main(String[] args) {
        if (args.length == 1) {
            new CompressNonGenericXz().compress(args[0]);
            return;
        }
        System.out.println("Usage: java CompressNonGenericXz <archive>");
    }

    private void compress(String filename) {
        boolean success = false;
        RandomAccessFile raf = null;
        IOutCreateArchiveXz outArchive = null;
        content = CompressArchiveStructure.create()[0].getContent();
        try {
            raf = new RandomAccessFile(filename, "rw");

            // Open out-archive object
            outArchive = SevenZip.openOutArchiveXz();

            // Configure archive
            outArchive.setLevel(5);

            // Create archive
            outArchive.createArchive(new RandomAccessFileOutStream(raf),
                    1, new MyCreateCallback());

            success = true;
        } catch (SevenZipException e) {
            System.err.println("Xz-Error occurs:");
            // Get more information using extended method
            e.printStackTraceExtended();
        } catch (Exception e) {
            System.err.println("Error occurs: " + e);
        } finally {
            if (outArchive != null) {
                try {
                    outArchive.close();
                } catch (IOException e) {
                    System.err.println("Error closing archive: " + e);
                    success = false;
                }
            }
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    System.err.println("Error closing file: " + e);
                    success = false;
                }
            }
        }
        if (success) {
            System.out.println("Compression operation succeeded");
        }
    }
}
Output
Compression operation succeeded

#Create a password-protected archive

Encrypt a 7z archive with a password (7z also encrypts the archive headers).

CompressWithPassword.java verified by CompressWithPasswordTest
import java.io.IOException;
import java.io.RandomAccessFile;

import net.sf.sevenzipjbinding.ICryptoGetTextPassword;
import net.sf.sevenzipjbinding.IOutCreateArchive7z;
import net.sf.sevenzipjbinding.IOutCreateCallback;
import net.sf.sevenzipjbinding.IOutItem7z;
import net.sf.sevenzipjbinding.ISequentialInStream;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.OutItemFactory;
import net.sf.sevenzipjbinding.impl.RandomAccessFileOutStream;
import net.sf.sevenzipjbinding.junit.snippets.CompressArchiveStructure.Item;
import net.sf.sevenzipjbinding.util.ByteArrayStream;

public class CompressWithPassword {
    /**
     * The callback provides information about archive items.
     *
     * It also implements
     * <ul>
     * <li>{@link ICryptoGetTextPassword}
     * </ul>
     * to provide a password for encryption.
     */
    private final class MyCreateCallback 
            implements IOutCreateCallback<IOutItem7z>, ICryptoGetTextPassword {
        public void setOperationResult(boolean operationResultOk)
                throws SevenZipException {
            // Track each operation result here
        }

        public void setTotal(long total) throws SevenZipException {
            // Track operation progress here
        }

        public void setCompleted(long complete) throws SevenZipException {
            // Track operation progress here
        }

        public IOutItem7z getItemInformation(int index,
                OutItemFactory<IOutItem7z> outItemFactory) {
            IOutItem7z item = outItemFactory.createOutItem();

            if (items[index].getContent() == null) {
                // Directory
                item.setPropertyIsDir(true);
            } else {
                // File
                item.setDataSize((long) items[index].getContent().length);
            }

            item.setPropertyPath(items[index].getPath());

            return item;
        }

        public ISequentialInStream getStream(int i) throws SevenZipException {
            if (items[i].getContent() == null) {
                return null;
            }
            return new ByteArrayStream(items[i].getContent(), true);
        }

        public String cryptoGetTextPassword() throws SevenZipException {
            return password;
        }
    }

    private Item[] items;
    private String password;

    public static void main(String[] args) {
        if (args.length  == 2) {
            new CompressWithPassword().compress(args[0], args[1]);
            return;
        }
        System.out.println("Usage: java CompressWithPassword <archive> <pass>");
    }

    private void compress(String filename, String pass) {
        items = CompressArchiveStructure.create();
        password = pass;

        boolean success = false;
        RandomAccessFile raf = null;
        IOutCreateArchive7z outArchive = null;
        try {
            raf = new RandomAccessFile(filename, "rw");

            // Open out-archive object
            outArchive = SevenZip.openOutArchive7z();

            // Header encryption is only available for 7z
            outArchive.setHeaderEncryption(true);

            // Create archive
            outArchive.createArchive(new RandomAccessFileOutStream(raf),
                    items.length, new MyCreateCallback());

            success = true;
        } catch (SevenZipException e) {
            System.err.println("7z-Error occurs:");
            // Get more information using extended method
            e.printStackTraceExtended();
        } catch (Exception e) {
            System.err.println("Error occurs: " + e);
        } finally {
            if (outArchive != null) {
                try {
                    outArchive.close();
                } catch (IOException e) {
                    System.err.println("Error closing archive: " + e);
                    success = false;
                }
            }
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    System.err.println("Error closing file: " + e);
                    success = false;
                }
            }
        }
        if (success) {
            System.out.println("Compression operation succeeded");
        }
    }
}
Output
Compression operation succeeded

#Compress a String to a byte array

Fully in-memory round trip: no files touched at all.

CompressMessage.java verified by CompressMessageTest
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Date;

import net.sf.sevenzipjbinding.IOutCreateArchiveZip;
import net.sf.sevenzipjbinding.IOutCreateCallback;
import net.sf.sevenzipjbinding.IOutItemZip;
import net.sf.sevenzipjbinding.ISequentialInStream;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.OutItemFactory;
import net.sf.sevenzipjbinding.impl.RandomAccessFileOutStream;
import net.sf.sevenzipjbinding.util.ByteArrayStream;

public class CompressMessage {
    /**
     * The callback provides information about archive items
     */
    static class MyCreateCallback implements IOutCreateCallback<IOutItemZip> {
        private final byte[] bytesToCompress;

        private MyCreateCallback(byte[] bytesToCompress) {
            this.bytesToCompress = bytesToCompress;
        }

        public void setOperationResult(boolean operationResultOk) {
            // called for each archive item
        }

        public void setTotal(long total) {
            // Track operation progress here
        }

        public void setCompleted(long complete) {
            // Track operation progress here
        }

        public IOutItemZip getItemInformation(int index,
                OutItemFactory<IOutItemZip> outItemFactory) {
            IOutItemZip outItem = outItemFactory.createOutItem();

            outItem.setDataSize((long) bytesToCompress.length);

            // Set name of the file in the archive
            outItem.setPropertyPath("message.txt");
            outItem.setPropertyCreationTime(new Date());

            // To get u+rw permissions on linux, if extracting with "unzip"
            // outItem.setPropertyAttributes(Integer.valueOf(0x81808000));

            return outItem;
        }

        public ISequentialInStream getStream(int index) {
            return new ByteArrayStream(bytesToCompress, true);
        }
    }

    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println("Usage: java CompressMessage <archive> <msg>");
            return;
        }

        final byte[] bytesToCompress = args[1].getBytes();

        RandomAccessFile raf = null;
        IOutCreateArchiveZip outArchive = null;
        try {
            raf = new RandomAccessFile(args[0], "rw");

            outArchive = SevenZip.openOutArchiveZip();
            outArchive.setLevel(5);
            outArchive.createArchive(new RandomAccessFileOutStream(raf), 1, 
                    new MyCreateCallback(bytesToCompress));

            System.out.println("Compression operation succeeded");
        } catch (SevenZipException e) {
            System.err.println("7-Zip-JBinding-Error:");
            // Extended stack trace prints more information
            e.printStackTraceExtended();
        } catch (Exception e) {
            System.err.println("Error occurs: " + e);
        } finally {
            if (outArchive != null) {
                try {
                    outArchive.close();
                } catch (IOException e) {
                    System.err.println("Error closing archive: " + e);
                }
            }
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    System.err.println("Error closing file: " + e);
                }
            }
        }
    }
}
Output
Compression operation succeeded

#Handle errors during compression

What proper SevenZipException handling looks like when a callback throws.

CompressWithError.java verified by CompressWithErrorTest
import java.io.IOException;
import java.io.RandomAccessFile;

import net.sf.sevenzipjbinding.IOutCreateArchiveTar;
import net.sf.sevenzipjbinding.IOutCreateCallback;
import net.sf.sevenzipjbinding.IOutItemTar;
import net.sf.sevenzipjbinding.ISequentialInStream;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.OutItemFactory;
import net.sf.sevenzipjbinding.impl.RandomAccessFileOutStream;
import net.sf.sevenzipjbinding.junit.snippets.CompressArchiveStructure.Item;
import net.sf.sevenzipjbinding.util.ByteArrayStream;

public class CompressWithError {
    /**
     * The callback provides information about archive items.
     */
    private final class MyCreateCallback 
            implements IOutCreateCallback<IOutItemTar> {

        public void setOperationResult(boolean operationResultOk)
                throws SevenZipException {
            // Track each operation result here
        }

        public void setTotal(long total) throws SevenZipException {
            // Track operation progress here
        }

        public void setCompleted(long complete) throws SevenZipException {
            // Track operation progress here
        }

        public IOutItemTar getItemInformation(int index,
                OutItemFactory<IOutItemTar> outItemFactory) {
            IOutItemTar item = outItemFactory.createOutItem();

            if (items[index].getContent() == null) {
                // Directory
                item.setPropertyIsDir(true);
            } else {
                // File
                item.setDataSize((long) items[index].getContent().length);
            }

            item.setPropertyPath(items[index].getPath());

            if (index == 1) {
                item.setDataSize(null); // Provide invalid data for item 1
            }

            return item;
        }

        public ISequentialInStream getStream(int i) throws SevenZipException {
            if (items[i].getContent() == null) {
                return null;
            }
            return new ByteArrayStream(items[i].getContent(), true);
        }
    }

    private Item[] items;

    public static void main(String[] args) {
        if (args.length == 1) {
            new CompressWithError().compress(args[0]);
            return;
        }
        System.out.println("Usage: java CompressNonGenericTar <archive>");
    }


    private void compress(String filename) {
        items = CompressArchiveStructure.create();

        boolean success = false;
        RandomAccessFile raf = null;
        IOutCreateArchiveTar outArchive = null;
        try {
            raf = new RandomAccessFile(filename, "rw");

            // Open out-archive object
            outArchive = SevenZip.openOutArchiveTar();

            // Activate tracing
            outArchive.setTrace(true);

            // Create archive
            outArchive.createArchive(new RandomAccessFileOutStream(raf),
                    items.length, new MyCreateCallback());

            success = true;
        } catch (SevenZipException e) {
            System.err.println("Tar-Error occurs:");
            // Get more information using extended method
            e.printStackTraceExtended();
        } catch (Exception e) {
            System.err.println("Error occurs: " + e);
        } finally {
            if (outArchive != null) {
                try {
                    outArchive.close();
                } catch (IOException e) {
                    System.err.println("Error closing archive: " + e);
                    success = false;
                }
            }
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    System.err.println("Error closing file: " + e);
                    success = false;
                }
            }
        }
        if (success) {
            System.out.println("Compression operation succeeded");
        }
    }
}
Output
0x80070057 (Invalid argument). Error creating 'tar' archive with 5 items

Updating archives

#Add and remove items in an existing archive

Modify an archive without repacking untouched items.

UpdateAddRemoveItems.java verified by UpdateAddRemoveItemsTest
import java.io.Closeable;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

import net.sf.sevenzipjbinding.IInArchive;
import net.sf.sevenzipjbinding.IInStream;
import net.sf.sevenzipjbinding.IOutCreateCallback;
import net.sf.sevenzipjbinding.IOutItemAllFormats;
import net.sf.sevenzipjbinding.IOutUpdateArchive;
import net.sf.sevenzipjbinding.ISequentialInStream;
import net.sf.sevenzipjbinding.PropID;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.OutItemFactory;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.impl.RandomAccessFileOutStream;
import net.sf.sevenzipjbinding.util.ByteArrayStream;

public class UpdateAddRemoveItems {
    /**
     * The callback defines the modification to be made.
     */
    private final class MyCreateCallback 
            implements IOutCreateCallback<IOutItemAllFormats> {

        public void setOperationResult(boolean operationResultOk)
                throws SevenZipException {
            // Track each operation result here
        }

        public void setTotal(long total) throws SevenZipException {
            // Track operation progress here
        }

        public void setCompleted(long complete) throws SevenZipException {
            // Track operation progress here
        }

        public IOutItemAllFormats getItemInformation(int index,
                OutItemFactory<IOutItemAllFormats> outItemFactory) 
                throws SevenZipException {
            if (index == itemToAdd) {
                // Adding new item
                IOutItemAllFormats outItem = outItemFactory.createOutItem();
                outItem.setPropertyPath(itemToAddPath);
                outItem.setDataSize((long) itemToAddContent.length);

                return outItem;
            }

            // Remove item by changing the mapping "new index"->"old index"
            if (index < itemToRemove) {
                return outItemFactory.createOutItem(index);
            }
            return outItemFactory.createOutItem(index + 1);
        }

        public ISequentialInStream getStream(int i) throws SevenZipException {
            if (i != itemToAdd) {
                return null;
            }
            return new ByteArrayStream(itemToAddContent, true);
        }
    }

    int itemToAdd; // New index of the item to add
    String itemToAddPath;
    byte[] itemToAddContent;

    int itemToRemove; // Old index of the item to be removed

    private void initUpdate(IInArchive inArchive) throws SevenZipException {
        itemToAdd = inArchive.getNumberOfItems() - 1;
        itemToAddPath = "data.dmp";
        itemToAddContent = "dmp-content".getBytes();

        itemToRemove = -1;
        for (int i = 0; i < inArchive.getNumberOfItems(); i++) {
            if (inArchive.getProperty(i, PropID.PATH).equals("info.txt")) {
                itemToRemove = i;
                break;
            }
        }
        if (itemToRemove == -1) {
            throw new RuntimeException("Item 'info.txt' not found");
        }
    }

    public static void main(String[] args) {
        if (args.length == 2) {
            new UpdateAddRemoveItems().compress(args[0], args[1]);
            return;
        }
        System.out.println("Usage: java UpdateAddRemoveItems <in> <out>");
    }

    private void compress(String in, String out) {
        boolean success = false;
        RandomAccessFile inRaf = null;
        RandomAccessFile outRaf = null;
        IInArchive inArchive;
        IOutUpdateArchive<IOutItemAllFormats> outArchive = null;
        List<Closeable> closeables = new ArrayList<Closeable>();
        try {
            // Open input file
            inRaf = new RandomAccessFile(in, "r");
            closeables.add(inRaf);
            IInStream inStream = new RandomAccessFileInStream(inRaf);

            // Open in-archive
            inArchive = SevenZip.openInArchive(null, inStream);
            closeables.add(inArchive);

            initUpdate(inArchive);

            outRaf = new RandomAccessFile(out, "rw");
            closeables.add(outRaf);

            // Open out-archive object
            outArchive = inArchive.getConnectedOutArchive();

            // Modify archive
            outArchive.updateItems(new RandomAccessFileOutStream(outRaf),
                    inArchive.getNumberOfItems(), new MyCreateCallback());

            success = true;
        } catch (SevenZipException e) {
            System.err.println("7z-Error occurs:");
            // Get more information using extended method
            e.printStackTraceExtended();
        } catch (Exception e) {
            System.err.println("Error occurs: " + e);
        } finally {
            for (int i = closeables.size() - 1; i >= 0; i--) {
                try {
                    closeables.get(i).close();
                } catch (Throwable e) {
                    System.err.println("Error closing resource: " + e);
                    success = false;
                }
            }
        }
        if (success) {
            System.out.println("Update successful");
        }
    }
}
Output
Update successful

#Alter existing items (content & properties)

Replace an item’s data and change its metadata in place.

UpdateAlterItems.java verified by UpdateAlterItemsTest
import java.io.Closeable;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

import net.sf.sevenzipjbinding.IInArchive;
import net.sf.sevenzipjbinding.IInStream;
import net.sf.sevenzipjbinding.IOutCreateCallback;
import net.sf.sevenzipjbinding.IOutItemAllFormats;
import net.sf.sevenzipjbinding.IOutUpdateArchive;
import net.sf.sevenzipjbinding.ISequentialInStream;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.OutItemFactory;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.impl.RandomAccessFileOutStream;
import net.sf.sevenzipjbinding.util.ByteArrayStream;

public class UpdateAlterItems {
    /**
     * The callback defines the modification to be made.
     */
    private final class MyCreateCallback 
            implements IOutCreateCallback<IOutItemAllFormats> {

        public void setOperationResult(boolean operationResultOk)
                throws SevenZipException {
            // Track each operation result here
        }

        public void setTotal(long total) throws SevenZipException {
            // Track operation progress here
        }

        public void setCompleted(long complete) throws SevenZipException {
            // Track operation progress here
        }

        public IOutItemAllFormats getItemInformation(int index,
                OutItemFactory<IOutItemAllFormats> outItemFactory) 
                throws SevenZipException {
            if (index != 2) {
                // Keep properties and content
                return outItemFactory.createOutItem(index);
            }

            IOutItemAllFormats item;
            item = outItemFactory.createOutItemAndCloneProperties(index);

            // Change property PATH
            item.setUpdateIsNewProperties(true);
            item.setPropertyPath("info2.txt");

            // Change content
            item.setUpdateIsNewData(true);
            item.setDataSize((long) NEW_CONTENT.length);

            return item;
        }

        public ISequentialInStream getStream(int i) throws SevenZipException {
            if (i != 2) {
                return null;
            }
            return new ByteArrayStream(NEW_CONTENT, true);
        }
    }

    static final byte[] NEW_CONTENT = "More Info!".getBytes();

    public static void main(String[] args) {
        if (args.length == 2) {
            new UpdateAlterItems().compress(args[0], args[1]);
            return;
        }
        System.out.println("Usage: java UpdateAlterItems <in-arc> <out-arc>");
    }


    private void compress(String in, String out) {
        boolean success = false;
        RandomAccessFile inRaf = null;
        RandomAccessFile outRaf = null;
        IInArchive inArchive;
        IOutUpdateArchive<IOutItemAllFormats> outArchive = null;
        List<Closeable> closeables = new ArrayList<Closeable>();
        try {
            // Open input file
            inRaf = new RandomAccessFile(in, "r");
            closeables.add(inRaf);
            IInStream inStream = new RandomAccessFileInStream(inRaf);

            // Open in-archive
            inArchive = SevenZip.openInArchive(null, inStream);
            closeables.add(inArchive);

            outRaf = new RandomAccessFile(out, "rw");
            closeables.add(outRaf);

            // Open out-archive object
            outArchive = inArchive.getConnectedOutArchive();

            // Modify archive
            outArchive.updateItems(new RandomAccessFileOutStream(outRaf),
                    inArchive.getNumberOfItems(), new MyCreateCallback());

            success = true;
        } catch (SevenZipException e) {
            System.err.println("7z-Error occurs:");
            // Get more information using extended method
            e.printStackTraceExtended();
        } catch (Exception e) {
            System.err.println("Error occurs: " + e);
        } finally {
            for (int i = closeables.size() - 1; i >= 0; i--) {
                try {
                    closeables.get(i).close();
                } catch (Throwable e) {
                    System.err.println("Error closing resource: " + e);
                    success = false;
                }
            }
        }
        if (success) {
            System.out.println("Update successful");
        }
    }
}
Output
Update successful