Java Deflate Byte Array deflate(String text, String encode)

Here you can find the source of deflate(String text, String encode)

Description

Deflates (compresses) the specified text.

License

Open Source License

Parameter

Parameter Description
text Text to encode
encode Encode type. If null, "UTF-8".

Exception

Parameter Description
IOException Thrown if a stream error occurs

Return

Byte array of compressed data

Declaration

public static byte[] deflate(String text, String encode)
        throws IOException 

Method Source Code

//package com.java2s;
/*//w w  w  . j  a  v  a2  s  . c o m
 * Copyright (c) 2013-2015 Netcrest Technologies, LLC. All rights reserved.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.util.zip.Deflater;

public class Main {
    /**
     * Deflates (compresses) the specified text.
     * 
     * @param text
     *            Text to encode
     * @param encode
     *            Encode type. If null, "UTF-8".
     * @return Byte array of compressed data
     * @throws IOException
     *             Thrown if a stream error occurs
     */
    public static byte[] deflate(String text, String encode)
            throws IOException {
        if (encode == null) {
            encode = "utf-8";
        }
        byte[] input = text.getBytes(encode);
        Deflater deflater = new Deflater();
        deflater.setInput(input);
        deflater.finish();
        ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);
        byte[] buf = new byte[20000];
        while (!deflater.finished()) {
            int bytesCompressed = deflater.deflate(buf);
            bos.write(buf, 0, bytesCompressed);
        }
        bos.close();
        byte[] compressedData = bos.toByteArray();
        return compressedData;
    }
}

Related

  1. deflate(byte[] data, byte[] dictionary)
  2. deflate(byte[] in)
  3. deflate(byte[] input)
  4. deflate(final byte[] pInput)
  5. deflate(String inString)
  6. deflateBuffer(byte[] uncompressedBuffer)
  7. deflateByteArray(final byte[] array)
  8. deflateGzip(byte[] inputBytes)
  9. deflateGzip(final byte[] bts)