Saturday, December 11, 2010

Compress in JavaMe

In scenarios where the amount of transmitted data is relevant, you should probably need to do some data compression on server side before sending information to the mobile client.

On server side, there is no problem to compress data. You can use or to read compressed data from a stream or to write data and compress it to a stream respectively.

On mobile client side (JavaMe), there is not such package as and therefore we are going to need some third party libraries in order to handle the compression. In this post we are going to use TinyLine GZIPInputStream which is part of the TinyLine Utils, you can find the binaries in the following link:

The library is about 9KB and it has only the GZIPInputStream class, there is no support for the GZIPOutputStream. But if you think about it, the major data transmition occurs from the server to the mobile client so having an InputStream is more important than having an OuputStream on the mobile client side.

Once you have added the library to your mobile application, you can make use of com.tinyline.util.GZIPInputStream class in order to receive the compressed data form the server. As I mentioned on my last post, I'm just showing the relevant code so the post can be easier to read:


     * Decompress the data received in the Stream. The stream is not closed in this method.
     * @param in <code>InputStream</code> of the connection where the
     * compressed data is received.
     * @return <code>String</code> representing the data decompressed
     * @throws IOException if there is any error during reading
    public static String deCompress(InputStream in) throws IOException {
        StringBuffer sb = new StringBuffer();

        GZIPInputStream gz = new GZIPInputStream(in);
        int c = 0;
        while ((c = != -1) {
            sb.append((char) c);


        return sb.toString();

It is pretty simple and it works OK. There is another library, JAZZLIB, wich implements both GZIPInputStream and GZIPOutputStream, but it takes about 41KB. If you think that your application sends as much data as it receives from the server, maybe it will be worth it to compress the data on the mobile client side too. In the next post we will make an example using this library and then we will improve our JSON example to use compression.

see ya soon!


TinyLine Utils. 2010. TinyLine [online].
Available on Internet:
[accessed on December 11 2010].