Java String Encode by Charset deflate(int level, String str, Charset encoding)

Here you can find the source of deflate(int level, String str, Charset encoding)

Description

deflate

License

Open Source License

Declaration

public static final byte[] deflate(int level, String str, Charset encoding)
            throws UnsupportedEncodingException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

import java.util.zip.Deflater;

public class Main {
    private static final int MAX_THREAD_BUFFERS = 100;
    private static final int THREAD_BUFFER_LENGTH = 1000;
    private static final Object _lock = new Object();
    private static final Map<Long, byte[]> _threadBuffers = new HashMap<>();
    private static final Queue<Long> _threadQueue = new LinkedList<>();

    public static final byte[] deflate(int level, String str, Charset encoding)
            throws UnsupportedEncodingException {

        // string to bytes
        byte[] bytes = str.getBytes(encoding);

        // deflate bytes
        Deflater def = new Deflater(level, true);
        def.reset();//  w  w w . j av a2  s .c om
        def.setInput(bytes);
        def.finish();

        // get thread buffer
        byte[] buffer = getThreadBuffer();

        // write deflated output
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while (!def.finished()) {
            int n = def.deflate(buffer);
            baos.write(buffer, 0, n);
        }
        baos.write(new byte[1], 0, 1);

        // get and return result
        byte[] result = baos.toByteArray();
        return result;
    }

    private static final byte[] getThreadBuffer() {

        byte[] buffer;
        synchronized (_lock) {

            // get thread buffer
            Long threadId = Thread.currentThread().getId();
            buffer = _threadBuffers.get(threadId);
            if (buffer == null) {
                buffer = new byte[THREAD_BUFFER_LENGTH];
                _threadBuffers.put(threadId, buffer);
                _threadQueue.add(threadId);
            }

            // throw away old buffers
            while (_threadQueue.size() > MAX_THREAD_BUFFERS) {
                Long removeThreadId = _threadQueue.poll();
                _threadBuffers.remove(removeThreadId);
            }
        }

        return buffer;
    }
}

Related

  1. canEncode(String charset, CharSequence text, String unicodeValue)
  2. canEncode(String sz, String charset)
  3. charsetForNameOrDefault(String encoding)
  4. checkEncoder(CharsetEncoder encoder)
  5. encode(Charset charset, String string)
  6. encode(final String str, final Charset charset)
  7. encode(String charsetName, char[] chars, int offset, int length)
  8. encode(String s, Charset encoding)