集册 Java实例教程 用GZIP压缩字符串

用GZIP压缩字符串

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

506
用GZIP压缩字符串


//package com.nowjava;//来自 n o w j a v a . c o m


import java.io.ByteArrayOutputStream;

import java.io.IOException;


import java.nio.ByteBuffer;


import java.util.zip.GZIPOutputStream;


public class Main {

    public static byte[] compress(String string) throws IOException {

        byte[] blockcopy = ByteBuffer.allocate(4)

                .order(java.nio.ByteOrder.LITTLE_ENDIAN)

                .putInt(string.length()).array();

        ByteArrayOutputStream os = new ByteArrayOutputStream(

                string.length());

        GZIPOutputStream gos = new GZIPOutputStream(os);

        gos.write(string.getBytes());

        gos.close();

        os.close();

        byte[] compressed = new byte[4 + os.toByteArray().length];/*from N o w J a v a . c o m*/

    
展开阅读全文