Compression / Decompression of Strings using the deflater

浪子不回头ぞ 提交于 2019-12-05 19:53:55

How you considered using the higher level api like Gzip.

Here is an example for compressing:

public static byte[] compressToByte(final String data, final String encoding)
    throws IOException
{
    if (data == null || data.length == 0)
    {
        return null;
    }
    else
    {
        byte[] bytes = data.getBytes(encoding);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPOutputStream os = new GZIPOutputStream(baos);
        os.write(bytes, 0, bytes.length);
        os.close();
        byte[] result = baos.toByteArray();
        return result;
    }
}

Here is an example for uncompressing:

public static String unCompressString(final byte[] data, final String encoding)
    throws IOException
{
    if (data == null || data.length == 0)
    {
        return null;
    }
    else
    {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        GZIPInputStream is = new GZIPInputStream(bais);
        byte[] tmp = new byte[256];
        while (true)
        {
            int r = is.read(tmp);
            if (r < 0)
            {
                break;
            }
            buffer.write(tmp, 0, r);
        }
        is.close();

        byte[] content = buffer.toByteArray();
        return new String(content, 0, content.length, encoding);
    }
}

We get very good performance and compression ratio with this.

The zip api is also an option.

Your comments are the correct answer.

In general, if a method is going to be used frequently, you want to eliminate any allocations and copying of data. This often means removing instance initialization and other setup to either static variables or to the constructor.

Using statics is easier, but you may run into lifetime issues (as in how do you know when to clean up the statics - do they exist forever?).

Doing the setup and initialization in the constructor allows the user of the class to determine the lifetime of the object and clean up appropriately. You could instantiate it once before going into a processing loop and GC it after exiting.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!