Class Deflater
public class Deflater extends Object
It is usually more convenient to use DeflaterOutputStream.
To compress an in-memory byte[] to another in-memory byte[] manually:
byte[] originalBytes = ...
Deflater deflater = new Deflater();
deflater.setInput(originalBytes);
deflater.finish();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
while (!deflater.finished()) {
int byteCount = deflater.deflate(buf);
baos.write(buf, 0, byteCount);
}
deflater.end();
byte[] compressedBytes = baos.toByteArray();
In situations where you don't have all the input in one array (or have so much
input that you want to feed it to the deflater in chunks), it's possible to call
setInput repeatedly, but you're much better off using
DeflaterOutputStream to handle all this for you. DeflaterOutputStream also helps
minimize memory requirements — the sample code above is very expensive.
Compression levels
A compression level must be DEFAULT_COMPRESSION to compromise between speed and
compression (currently equivalent to level 6), or between 0 (NO_COMPRESSION, where
the input is simply copied) and 9 (BEST_COMPRESSION). Level 1 (BEST_SPEED)
performs some compression, but with minimal speed overhead.
-
Field Summary
Fields Modifier and Type Field Description static intBEST_COMPRESSIONThis compression level gives the best compression, but takes the most time.static intBEST_SPEEDThis compression level gives minimal compression, but takes the least time (of any level that actually performs compression; seeNO_COMPRESSION).static intDEFAULT_COMPRESSIONThe default compression level.static intDEFAULT_STRATEGYThe default compression strategy.static intDEFLATEDThe default compression method.static intFILTEREDA compression strategy.static intFULL_FLUSHFlush buffers so recipients can immediately decode the data sent thus far.static intHUFFMAN_ONLYA compression strategy.static intNO_COMPRESSIONThis compression level does no compression.static intNO_FLUSHUse buffering for best compression.static intSYNC_FLUSHFlush buffers so recipients can immediately decode the data sent thus far. -
Constructor Summary
Constructors Constructor Description Deflater()Constructs a newDeflaterinstance using the default compression level.Deflater(int level)Constructs a newDeflaterinstance with the given compression level.Deflater(int level, boolean noHeader)Constructs a newDeflaterinstance with the given compression level. -
Method Summary
Modifier and Type Method Description intdeflate(byte[] buf)Deflates the data (previously passed tosetInput) into the supplied buffer.intdeflate(byte[] buf, int offset, int byteCount)Deflates data (previously passed tosetInput) into a specific region within the supplied buffer.intdeflate(byte[] buf, int offset, int byteCount, int flush)Deflates data (previously passed tosetInput) into a specific region within the supplied buffer, optionally flushing the input buffer.voidend()Frees all resources held onto by this deflating algorithm.protected voidfinalize()Invoked when the garbage collector has detected that this instance is no longer reachable.voidfinish()Indicates to theDeflaterthat all uncompressed input has been provided to it.booleanfinished()intgetAdler()Returns theAdler32checksum of the uncompressed data read so far.longgetBytesRead()Returns the total number of bytes read by theDeflater.longgetBytesWritten()Returns a the total number of bytes written by thisDeflater.intgetTotalIn()Returns the total number of bytes of input read by thisDeflater.intgetTotalOut()Returns the total number of bytes written to the output buffer by thisDeflater.booleanneedsInput()Returns true ifsetInputmust be called before deflation can continue.voidreset()Resets theDeflaterto accept new input without affecting any previously made settings for the compression strategy or level.voidsetDictionary(byte[] dictionary)Sets the dictionary to be used for compression by thisDeflater.voidsetDictionary(byte[] buf, int offset, int byteCount)Sets the dictionary to be used for compression by thisDeflater.voidsetInput(byte[] buf)Sets the input buffer theDeflaterwill use to extract uncompressed bytes for later compression.voidsetInput(byte[] buf, int offset, int byteCount)Sets the input buffer theDeflaterwill use to extract uncompressed bytes for later compression.voidsetLevel(int level)Sets the given compression level to be used when compressing data.voidsetStrategy(int strategy)Sets the compression strategy to be used.
-
Field Details
-
BEST_COMPRESSION
public static final int BEST_COMPRESSIONThis compression level gives the best compression, but takes the most time.- See Also:
- Constant Field Values
-
BEST_SPEED
public static final int BEST_SPEEDThis compression level gives minimal compression, but takes the least time (of any level that actually performs compression; seeNO_COMPRESSION).- See Also:
- Constant Field Values
-
NO_COMPRESSION
public static final int NO_COMPRESSIONThis compression level does no compression. It is even faster thanBEST_SPEED.- See Also:
- Constant Field Values
-
DEFAULT_COMPRESSION
public static final int DEFAULT_COMPRESSIONThe default compression level. This is a trade-off between speed and compression, currently equivalent to level 6.- See Also:
- Constant Field Values
-
DEFAULT_STRATEGY
public static final int DEFAULT_STRATEGYThe default compression strategy.- See Also:
- Constant Field Values
-
DEFLATED
public static final int DEFLATEDThe default compression method.- See Also:
- Constant Field Values
-
FILTERED
public static final int FILTEREDA compression strategy.- See Also:
- Constant Field Values
-
HUFFMAN_ONLY
public static final int HUFFMAN_ONLYA compression strategy.- See Also:
- Constant Field Values
-
NO_FLUSH
public static final int NO_FLUSHUse buffering for best compression.- Since:
- 1.7
- See Also:
- Constant Field Values
-
SYNC_FLUSH
public static final int SYNC_FLUSHFlush buffers so recipients can immediately decode the data sent thus far. This mode may degrade compression.- Since:
- 1.7
- See Also:
- Constant Field Values
-
FULL_FLUSH
public static final int FULL_FLUSHFlush buffers so recipients can immediately decode the data sent thus far. The compression state is also reset to permit random access and recovery for clients who have discarded or damaged their own copy. This mode may degrade compression.- Since:
- 1.7
- See Also:
- Constant Field Values
-
-
Constructor Details
-
Deflater
public Deflater()Constructs a newDeflaterinstance using the default compression level. The compression strategy can be specified withsetStrategy(int). A header is added to the output by default; useDeflater(int, boolean)if you need to omit the header. -
Deflater
public Deflater(int level)Constructs a newDeflaterinstance with the given compression level. The compression strategy can be specified withsetStrategy(int). A header is added to the output by default; useDeflater(int, boolean)if you need to omit the header. -
Deflater
public Deflater(int level, boolean noHeader)Constructs a newDeflaterinstance with the given compression level. IfnoHeaderis true, no ZLIB header is added to the output. In a zip file, every entry (compressed file) comes with such a header. The strategy can be specified usingsetStrategy(int).
-
-
Method Details
-
deflate
public int deflate(byte[] buf)Deflates the data (previously passed tosetInput) into the supplied buffer.- Returns:
- number of bytes of compressed data written to
buf.
-
deflate
public int deflate(byte[] buf, int offset, int byteCount)Deflates data (previously passed tosetInput) into a specific region within the supplied buffer.- Returns:
- the number of bytes of compressed data written to
buf.
-
deflate
public int deflate(byte[] buf, int offset, int byteCount, int flush)Deflates data (previously passed tosetInput) into a specific region within the supplied buffer, optionally flushing the input buffer.- Parameters:
flush- one ofNO_FLUSH,SYNC_FLUSHorFULL_FLUSH.- Returns:
- the number of compressed bytes written to
buf. If this equalsbyteCount, the number of bytes of input to be flushed may have exceeded the output buffer's capacity. In this case, finishing a flush will require the output buffer to be drained and additional calls todeflate(byte[])to be made. - Throws:
IllegalArgumentException- ifflushis invalid.- Since:
- 1.7
-
end
public void end()Frees all resources held onto by this deflating algorithm. Any unused input or output is discarded. This method should be called explicitly in order to free native resources as soon as possible. Afterend()is called, other methods will typically throwIllegalStateException. -
finalize
protected void finalize()Description copied from class:ObjectInvoked when the garbage collector has detected that this instance is no longer reachable. The default implementation does nothing, but this method can be overridden to free resources.Note that objects that override
finalizeare significantly more expensive than objects that don't. Finalizers may be run a long time after the object is no longer reachable, depending on memory pressure, so it's a bad idea to rely on them for cleanup. Note also that finalizers are run on a single VM-wide finalizer thread, so doing blocking work in a finalizer is a bad idea. A finalizer is usually only necessary for a class that has a native peer and needs to call a native method to destroy that peer. Even then, it's better to provide an explicitclosemethod (and implementCloseable), and insist that callers manually dispose of instances. This works well for something like files, but less well for something like aBigIntegerwhere typical calling code would have to deal with lots of temporaries. Unfortunately, code that creates lots of temporaries is the worst kind of code from the point of view of the single finalizer thread.If you must use finalizers, consider at least providing your own
ReferenceQueueand having your own thread process that queue.Unlike constructors, finalizers are not automatically chained. You are responsible for calling
super.finalize()yourself.Uncaught exceptions thrown by finalizers are ignored and do not terminate the finalizer thread. See Effective Java Item 7, "Avoid finalizers" for more.
-
finish
public void finish()Indicates to theDeflaterthat all uncompressed input has been provided to it.- See Also:
finished
-
finished
public boolean finished() -
getAdler
public int getAdler()Returns theAdler32checksum of the uncompressed data read so far. -
getTotalIn
public int getTotalIn()Returns the total number of bytes of input read by thisDeflater. This method is limited to 32 bits; usegetBytesRead()instead. -
getTotalOut
public int getTotalOut()Returns the total number of bytes written to the output buffer by thisDeflater. The method is limited to 32 bits; usegetBytesWritten()instead. -
needsInput
public boolean needsInput() -
reset
public void reset()Resets theDeflaterto accept new input without affecting any previously made settings for the compression strategy or level. This operation must be called afterfinishedreturns true if theDeflateris to be reused. -
setDictionary
public void setDictionary(byte[] dictionary)Sets the dictionary to be used for compression by thisDeflater. This method can only be called if thisDeflatersupports the writing of ZLIB headers. This is the default, but can be overridden usingDeflater(int, boolean). -
setDictionary
public void setDictionary(byte[] buf, int offset, int byteCount)Sets the dictionary to be used for compression by thisDeflater. This method can only be called if thisDeflatersupports the writing of ZLIB headers. This is the default, but can be overridden usingDeflater(int, boolean). -
setInput
public void setInput(byte[] buf)Sets the input buffer theDeflaterwill use to extract uncompressed bytes for later compression. -
setInput
public void setInput(byte[] buf, int offset, int byteCount)Sets the input buffer theDeflaterwill use to extract uncompressed bytes for later compression. -
setLevel
public void setLevel(int level)Sets the given compression level to be used when compressing data. This value must be set prior to callingsetInput.- Throws:
IllegalArgumentException- If the compression level is invalid.
-
setStrategy
public void setStrategy(int strategy)Sets the compression strategy to be used. The strategy must be one of FILTERED, HUFFMAN_ONLY or DEFAULT_STRATEGY. This value must be set prior to callingsetInput.- Throws:
IllegalArgumentException- If the strategy specified is not one of FILTERED, HUFFMAN_ONLY or DEFAULT_STRATEGY.
-
getBytesRead
public long getBytesRead()Returns the total number of bytes read by theDeflater. This method is the same asgetTotalIn()except that it returns alongvalue instead of an integer. -
getBytesWritten
public long getBytesWritten()Returns a the total number of bytes written by thisDeflater. This method is the same asgetTotalOutexcept it returns alongvalue instead of an integer.
-