集册 Java实例教程 使用Deflater压缩字节数组

使用Deflater压缩字节数组

欢马劈雪     最近更新时间:2020-01-02 10:19:05

612
使用Deflater压缩字节数组
/* from 时   代    Java - nowjava.com*/

import java.io.ByteArrayOutputStream;

import java.util.zip.Deflater;


public class Main {

  public static void main(String args[]) {

    String str = "this is a test";


    byte[] bytes = str.getBytes();


    Deflater deflater = new Deflater();


    deflater.setInput(bytes);


    deflater.finish();


    ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length);


    byte[] buffer = new byte[1024];
/** 时 代      J a v a   公   众 号 - nowjava.com 提 供 **/

    while (!deflater.finished()) {

      int bytesCompressed = deflater.deflate(buffer);

      bos.write(buffer, 0, bytesCompressed);

    }


    try {

      bos.close();

    } catch (Exception ioe) {

      System.out.println("Error while closing the stream : " + ioe);

    }


    byte[] compressedArray = bos.toByteArray();


    System.out.println(
展开阅读全文