Gzip Chilkat2 Java Reference Documentation

Gzip

Current Version: 11.7.0

Markdown version of this page for AI tools (v 11.7.0) · all AI docs

Chilkat.Gzip

Compress, decompress, inspect, and convert GZIP data in files or memory.

Chilkat.Gzip provides GZIP compression and decompression for file-based and in-memory workflows. It can compress and uncompress files, strings, byte arrays, BinData, and encoded data such as Base64 or hex. It also supports .tar.gz extraction, gzip metadata such as original filename, timestamp, and comments, and inspection of GZIP header information without fully expanding the compressed data.

File compression

Compress files to .gz, uncompress .gz files, and write decompressed output directly to disk.

Memory-based data

Work with byte arrays and Chilkat.BinData for applications that need compression or decompression without temporary files.

String workflows

Compress and uncompress strings with explicit charset handling for text data that must round-trip correctly.

Encoded GZIP data

Handle GZIP data represented as Base64, hex, or other supported encoded forms when binary data must be carried as text.

GZIP metadata

Set or inspect metadata such as original filename, modified time, comments, and extra data stored in the GZIP header.

Tar-gzip and XFDL

Extract .tar.gz archives and decode XFDL content that uses gzip-related encodings.

Common pattern: Use Gzip when the data is a single GZIP stream, a .gz file, or a .tar.gz archive. For ZIP archives, use Chilkat.Zip; for raw deflate or zlib-style compression, use Chilkat.Compression.

Object Creation

import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Gzip;

try (Gzip gzip = new Gzip()) {
    // ... use gzip ...
} catch (ChilkatException e) {
    System.out.println(e.getMessage());          // "Gzip.someMethod failed: <reason>"
    System.out.println(e.getLastErrorText());    // the full log of the failed call
}
public Gzip()

Creates the underlying native Chilkat object. The native library (chilkat2java) is loaded the first time any Chilkat2 object is created; see the README in the download for where it is looked for (-Dchilkat2.library.path, a classpath resource, or java.library.path).

public void close()

Releases the native object (Gzip is AutoCloseable, so try-with-resources calls it). Calling it again does nothing; any other method or property accessor called afterwards throws IllegalStateException. An object that is never closed is freed by a background cleaner once it becomes unreachable, but the garbage collector does not see native memory, so closing is the normal path. Objects returned by methods are owned by the caller too.

public boolean isClosed()

Returns true once close() has been called.

Errors

A method that fails throws ChilkatException, an unchecked exception carrying getClassName(), getMethodName(), getReason() (one line, also in the message) and getLastErrorText() (the full log, captured at the moment of the failure). The object remains usable. Methods that look something up and find nothing return null instead of throwing (each such method says so), and methods that answer a question (hasMember, isUnlocked, ...) return a plain boolean. Property accessors do not throw for Chilkat reasons.

A null string or object argument throws NullPointerException naming the parameter (except where a method documents that null is accepted), and a string containing U+0000 throws IllegalArgumentException.

Use an object from one thread at a time; it may be handed from one thread to another. The one cross-thread operation is setting setAbortCurrent(true) on an object that is busy in another thread (on the classes that have AbortCurrent). Unlocking: call new Global().unlockBundle("...") once at startup.

Properties

AbortCurrent
// read/write
boolean getAbortCurrent()
void setAbortCurrent(boolean value)
Introduced in version 9.5.0.58

Set this property to true to request that the currently running operation be aborted. This is useful for long-running operations such as large file compression or decompression. Methods that complete quickly are generally not affected.

If no method is currently running, the property is automatically reset to false when the next method begins. After an abort occurs, it is also reset to false. Both synchronous and asynchronous operations can be aborted. For synchronous calls, another thread must set this property.

top
Comment
// read/write
String getComment()
void setComment(String value)

An optional comment to embed in the Gzip file when a Compress* method is called.

More Information and Examples
top
CompressionLevel
// read/write
int getCompressionLevel()
void setCompressionLevel(int value)
Introduced in version 9.5.0.50

Controls the compression level used when creating Gzip data. The value can range from 0 to 9.

  • 0 = no compression
  • 9 = maximum compression

The default value is 6, which is a typical balance between compression size and speed. Higher levels may take significantly more CPU time while producing only slightly smaller output, depending on the data.

More Information and Examples
top
DebugLogFilePath
// read/write
String getDebugLogFilePath()
void setDebugLogFilePath(String value)

If set to a file path, this property logs the LastErrorText of each Chilkat method or property call to the specified file. This logging helps identify the context and history of Chilkat calls leading up to any crash or hang, aiding in debugging.

Enabling the VerboseLogging property provides more detailed information. This property is mainly used for debugging rare instances where a Chilkat method call causes a hang or crash, which should generally not happen.

Possible causes of hangs include:

  • A timeout property set to 0, indicating an infinite timeout.
  • A hang occurring within an event callback in the application code.
  • An internal bug in the Chilkat code causing the hang.

More Information and Examples
top
Filename
// read/write
String getFilename()
void setFilename(String value)

The filename to embed in the Gzip file when a Compress* method is called. Some Gzip extraction tools use this embedded filename as the default output filename.

More Information and Examples
top
HeartbeatMs
// read/write
int getHeartbeatMs()
void setHeartbeatMs(int value)

Specifies the interval, in milliseconds, between AbortCheck event callbacks. These callbacks allow an application to cancel certain long-running operations before they finish.

The default value is 0, which means no AbortCheck callbacks are triggered.

More Information and Examples
top
LastErrorHtml
// read-only
String getLastErrorHtml()

Provides HTML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastErrorText
// read-only
String getLastErrorText()

Provides plain text information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastErrorXml
// read-only
String getLastErrorXml()

Provides XML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastMethodSuccess
// read/write
boolean getLastMethodSuccess()
void setLastMethodSuccess(boolean value)

Indicates the success or failure of the most recent method call: true means success, false means failure. This property remains unchanged by property setters or getters. This method is present to address challenges in checking for null or Nothing returns in certain programming languages. Note: This property does not apply to methods that return integer values or to boolean-returning methods where the boolean does not indicate success or failure.

top
LastModStr
// read/write
String getLastModStr()
void setLastModStr(String value)

Specifies the last-modified date/time to embed in the Gzip file when a Compress* method is called.

The value must be provided as an RFC 822 formatted date/time string.

Example:

Sun, 12 Apr 2026 12:45:26 GMT

If this property is not set, the current system date/time is used automatically.

More Information and Examples
top
UseCurrentDate
// read/write
boolean getUseCurrentDate()
void setUseCurrentDate(boolean value)

Controls the last-modified date/time assigned to files created by Uncompress* methods.

When set to true, the extracted file uses the current date/time instead of the date/time stored in the Gzip data.

top
VerboseLogging
// read/write
boolean getVerboseLogging()
void setVerboseLogging(boolean value)

If set to true, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is false. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.

top
Version
// read-only
String getVersion()

Version of the component/library, such as "10.1.0"

More Information and Examples
top

Methods

CompressBd
void compressBd(BinData binDat)
Introduced in version 9.5.0.67

Compresses the contents of a BinData object in place, replacing the original data with Gzip-compressed data.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

More Information and Examples
top
CompressFile
void compressFile(String srcPath, String destPath)

Compresses a file and writes the result as a Gzip file, typically with a .gz extension.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

More Information and Examples
top
CompressFile2
void compressFile2(String srcPath, String embeddedFilename, String destPath)

Compresses a file and writes the result as a Gzip file, while allowing a different filename to be embedded inside the Gzip data.

The inFilename parameter is the actual file on disk. The srcPath parameter is the filename stored in the Gzip header and may be used by extraction tools as the output filename.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

More Information and Examples
top
CompressFileBd
void compressFileBd(String filePath, BinData bd)
Introduced in version 11.0.0

Compresses a file and stores the resulting Gzip data in a BinData object.

The compressed output is held in memory. The maximum compressed size is 4 GB.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
CompressSb
void compressSb(StringBuilder sb, String charset, BinData bd)
Introduced in version 11.0.0

Compresses the text contained in a StringBuilder and writes the Gzip-compressed result to a BinData object.

Before compression, the string is converted to bytes using the specified character set, such as utf-8, iso-8859-1, or shift_JIS.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
CompressStringENC
String compressStringENC(String inStr, String charset, String encoding)

Compresses a string and returns the Gzip-compressed data as an encoded string.

The input string is first converted to bytes using the specified character set. The compressed binary data is then encoded using the requested encoding, such as base64, hex, url, base32, or quoted-printable.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
CompressStringToFile
void compressStringToFile(String inStr, String destCharset, String destPath)

Compresses a string and writes the resulting Gzip data to a file.

The string is first converted to bytes using the character set specified by destCharset.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
GetGzipInfo
void getGzipInfo(String filePath, JsonObject json)
Introduced in version 11.5.0

Retrieves metadata stored in a Gzip file and returns the information in a JsonObject.

The metadata is returned using the following JSON structure:

{
  "extraData": "AAECAw==",
  "filename": "example.txt",
  "comment": "This is the comment"
}
  • filename – the original filename embedded in the Gzip file (if present)
  • comment – an optional descriptive comment (if present)
  • extraData – optional additional binary data, returned as a Base64-encoded string

Any of these fields may be omitted if they were not included when the Gzip file was created.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

More Information and Examples
top
GetGzipInfoBd
void getGzipInfoBd(BinData bd, JsonObject json)
Introduced in version 11.5.0

Retrieves metadata stored in Gzip data contained within a BinData object and returns the information in a JsonObject.

The metadata is returned using the same JSON structure:

{
  "extraData": "AAECAw==",
  "filename": "example.txt",
  "comment": "This is the comment"
}
  • filename – the original filename embedded in the Gzip data (if present)
  • comment – an optional descriptive comment (if present)
  • extraData – optional additional binary data, returned as a Base64-encoded string

Any of these fields may be omitted if they were not included when the Gzip data was created.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
IsGzip
boolean isGzip(BinData bd)
Introduced in version 11.0.0

Checks whether the data contained in a BinData object is in Gzip format.

Returns true if the data is Gzip-formatted, or false otherwise.

Never throws: false is an answer, not a failure.

top
SetDt
void setDt(DateTime dt)

Sets the last-modified date/time to embed in the Gzip file when a Compress* method is called.

If no date/time is explicitly set, the current system date/time is used.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

More Information and Examples
top
SetExtraData
void setExtraData(String encodedData, String encoding)
Introduced in version 11.0.0

Sets optional extra binary data to include in the Gzip header when a Compress* method is called.

The data is passed as an encoded string. Supported encodings include base64, hex, ascii, and many others.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
UncompressBd
void uncompressBd(BinData binDat)
Introduced in version 9.5.0.67

Decompresses Gzip data contained in a BinData object in place, replacing the compressed data with the uncompressed data.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

More Information and Examples
top
UncompressBdToFile
void uncompressBdToFile(BinData bd, String filePath)
Introduced in version 11.0.0

Decompresses Gzip data stored in a BinData object and writes the result to a file.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
UncompressFile
void uncompressFile(String srcPath, String destPath)

Decompresses a Gzip file and writes the result to the specified output path.

The output filename is provided by the caller. The filename embedded in the Gzip data is not used.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
UncompressFileToString
String uncompressFileToString(String srcPath, String charset)

Decompresses a Gzip file that contains text and returns the uncompressed text as a string.

The charset parameter specifies the character encoding of the uncompressed text, such as utf-8, iso-8859-1, windows-1252, shift_JIS, big5, etc.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
UncompressStringENC
String uncompressStringENC(String inStr, String charset, String encoding)

Decompresses Gzip data provided as an encoded string and returns the uncompressed result as text.

The input string is first decoded using the specified encoding, such as base64, hex, url, base32, quoted-printable, etc. The decoded Gzip data is then decompressed and converted to text using the specified character set.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

top
UnTarGz
void unTarGz(String gzPath, String destDir, boolean bNoAbsolute)

Extracts a .tar.gz archive to a directory.

The Gzip decompression and TAR extraction are performed in streaming mode. No temporary files are created, and memory usage remains small and constant.

If bNoAbsolute is true, absolute paths in the TAR archive are not allowed. This helps protect against extracting files to unsafe locations, such as system directories.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

More Information and Examples
top
XfdlToXml
String xfdlToXml(String xfldData)

Converts encoded and compressed XFDL data to a decompressed XML string.

XFDL data is often stored in an ASCII-safe compressed form, such as asci-gzip or asc-gzip. Despite the name, this does not always mean the data is a standard .gz file. In some XFDL files, the compressed payload uses the raw deflate format rather than the full Gzip file format.

Chilkat automatically detects the actual encoding and compression format used by the XFDL data. It decodes the ASCII/Base64 representation, determines whether the compressed data is Gzip or deflate, decompresses it correctly, and returns the resulting XML string.

This allows applications to call XfdlToXml without needing to manually distinguish between XFDL variants such as Base64+Gzip and Base64+Deflate.

Returns the decoded and decompressed XML string.

XFDL (Extensible Forms Description Language) is an XML-based format used to define secure, interactive electronic forms—often including digital signatures and integrity protections—commonly used in government and enterprise applications.

Throws ChilkatException on failure; e.getLastErrorText() (or the object's getLastErrorText()) explains why, and the object remains usable.

More Information and Examples
top

Events

All Chilkat methods are synchronous: the call returns when the work is done. During a long-running call, Gzip reports progress through a ProgressListener, an interface with three methods, each with a default, so you override only what you need:

import com.chilkatsoft.chilkat2.ProgressListener;

gzip.setProgressListener(new ProgressListener() {
    @Override public boolean percentDone(int pctDone) {
        System.out.println(pctDone + "%");
        return false;           // return true to abort the method in progress
    }
    @Override public void progressInfo(String name, String value) {
        System.out.println(name + ": " + value);
    }
});
gzip.setHeartbeatMs(250);   // abortCheck 4 times per second

For a single callback, a lambda is shorter:

gzip.onPercentDone(pct -> { System.out.println(pct + "%"); return false; });
public void setProgressListener(ProgressListener listener)

Installs listener as the receiver of this object's events, replacing any listener or lambda installed before; null removes it.

public ProgressListener getProgressListener()

Returns the installed listener, or null.

public void onAbortCheck(BooleanSupplier callback)
public void onPercentDone(IntPredicate callback)
public void onProgressInfo(BiConsumer<String, String> callback)

Each installs a listener whose only callback is the given lambda (from java.util.function). Like setProgressListener, each replaces the listener installed before, so to handle more than one event, implement ProgressListener. null removes the listener.

abortCheck is called at the interval set by the HeartbeatMs property (0, the default, disables it); percentDone is called when an operation's completion percentage is known; progressInfo delivers named progress values. Returning true from abortCheck or percentDone aborts the running method, which then throws ChilkatException.

Callbacks run on the thread that called the method, before it returns. Inside a callback, property accessors of the object (such as setAbortCurrent(true)) and other objects may be used, but calling a method of the same object throws IllegalStateException. An exception thrown by a callback aborts the running method and is rethrown from it; the object remains usable.

AbortCheck
// ProgressListener method (default returns false), or onAbortCheck(BooleanSupplier)
boolean abortCheck()

Enables a method call to be aborted by triggering the AbortCheck event at intervals defined by the HeartbeatMs property. If HeartbeatMs is set to its default value of 0, no events will occur. For instance, set HeartbeatMs to 200 to trigger 5 AbortCheck events per second.

More Information and Examples

Example

import java.util.concurrent.atomic.AtomicBoolean;

final AtomicBoolean stop = new AtomicBoolean(false);   // another thread may call stop.set(true)
gzip.setHeartbeatMs(250);                     // call abortCheck 4 times per second
gzip.onAbortCheck(() -> stop.get());
top
PercentDone
// ProgressListener method (default returns false), or onPercentDone(IntPredicate)
boolean percentDone(int pctDone)

This provides the percentage completion for any method involving network communications or time-consuming processing, assuming the progress can be measured as a percentage. This event is triggered only when it's possible and logical to express the operation's progress as a percentage. The pctDone argument will range from 1 to 100. For methods that finish quickly, the number of PercentDone callbacks may vary, but the final callback will have pctDone equal to 100. For longer operations, callbacks will not exceed one per percentage point (e.g., 1, 2, 3, ..., 98, 99, 100).

The PercentDone callback also acts as an AbortCheck event. For fast methods where PercentDone fires, an AbortCheck event may not trigger since the PercentDone callback already provides an opportunity to abort. For longer operations, where time between PercentDone callbacks is extended, AbortCheck callbacks enable more responsive operation termination.

To abort the operation, set the abort output argument to true. This will cause the method to terminate and return a failure status or corresponding failure value.

More Information and Examples

Example

gzip.onPercentDone(pct -> {
    // pct ranges from 0 to 100.
    System.out.println("Percent done: " + pct);
    return false;   // return true to abort the method in progress
});
top
ProgressInfo
// ProgressListener method (default does nothing), or onProgressInfo(BiConsumer<String, String>)
void progressInfo(String name, String value)

This event callback provides tag name/value pairs that detail what occurs during a method call. To discover existing tag names, create code to handle the event, emit the pairs, and review them. Most tag names are self-explanatory.

Note: Some Chilkat methods don't fire any ProgressInfo events.

More Information and Examples

Example

gzip.onProgressInfo((name, value) -> System.out.println(name + ": " + value));
top