Sample code for 30+ languages & platforms
Android™

Compress Text from StringBuilder to Gzip (BinData Output)

See more Gzip Examples

This example demonstrates how to use the CompressSb method to compress text stored in a StringBuilder into Gzip format.

The text is first converted to its byte representation using the specified character set (in this case, UTF-8). These bytes are then compressed, and the resulting Gzip data is written to a BinData object in memory.

This approach is useful when working with dynamically generated text that you want to compress without first writing it to a file. The example also shows how the compressed data can optionally be saved to a .gz file.

Chilkat Android™ Downloads

Android™
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;

import android.app.Activity;
import com.chilkatsoft.*;

import android.widget.TextView;
import android.os.Bundle;

public class SimpleActivity extends Activity {

  private static final String TAG = "Chilkat";

  // Called when the activity is first created.
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean success = false;

    // This example demonstrates how to compress text contained in a StringBuilder
    // into Gzip format, storing the compressed result in a BinData object.

    CkGzip gzip = new CkGzip();
    CkStringBuilder sb = new CkStringBuilder();
    CkBinData bd = new CkBinData();

    // Add some text to the StringBuilder:
    sb.Append("The quick brown fox jumps over the lazy dog.");

    // Compress the text using UTF-8 encoding:
    success = gzip.CompressSb(sb,"utf-8",bd);
    if (success == false) {
        Log.i(TAG, gzip.lastErrorText());
        return;
        }

    // The BinData now contains the Gzip-compressed bytes.
    Log.i(TAG, "Compression successful.");
    Log.i(TAG, "Compressed size (bytes): " + String.valueOf(bd.get_NumBytes()));

    // (Optional) Save to a .gz file:
    success = bd.WriteFile("text.gz");
    if (success == false) {
        Log.i(TAG, bd.lastErrorText());
        return;
        }

    Log.i(TAG, "Gzip file written to text.gz");

  }

  static {
      System.loadLibrary("chilkat");

      // Note: If the incorrect library name is passed to System.loadLibrary,
      // then you will see the following error message at application startup:
      //"The application <your-application-name> has stopped unexpectedly. Please try again."
  }
}