Zip compress byte array - Java java.lang

Java examples for java.lang:byte Array Compress

Description

Zip compress byte array

Demo Code

/****************************************************************************
 * Copyright (c) 2007 Composent, Inc. and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:// w  w  w .  j a  va  2  s .c o  m
 *    Composent, Inc. - initial API and implementation
 *****************************************************************************/
//package com.java2s;
import java.io.*;
import java.util.zip.*;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] source = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(java.util.Arrays.toString(compress(source)));
    }

    public static byte[] compress(byte[] source) throws IOException {
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        final ZipOutputStream zos = new ZipOutputStream(bos);
        final ByteArrayInputStream bis = new ByteArrayInputStream(source);
        int read = 0;
        final byte[] buf = new byte[16192];
        zos.putNextEntry(new ZipEntry("bytes")); //$NON-NLS-1$
        while ((read = bis.read(buf)) != -1) {
            zos.write(buf, 0, read);
        }
        zos.finish();
        zos.flush();
        return bos.toByteArray();
    }
}

Related Tutorials