如何gzip然后解压缩字符串而不用Java中的文件系统?

时间:2016-08-18 02:23:54

标签: java gzip gzipinputstream gzipoutputstream

所需
创建压缩并解压缩字符串或字节数组。 之后我计划将Base64编码为写入日志文件。

不幸的是,它似乎没有将其识别为压缩或其他东西。 我假设它缺少一些元数据字节,但找不到我需要的东西。

输出: enter image description here

测试类:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import org.apache.commons.codec.binary.Base64;

public class TestEncodeDecode {
    private static final String UTF_8 = "UTF-8";

    public static void main(String[] args) throws IOException {
        String originalString = "     This online sample demonstrates functionality of a base64 property, ByteArray class and Huge asp file upload.\n      The sample uses a special Base64 algorithm written for the ByteArray class.";

        System.out.println(originalString);
        System.out.println("------------------------------------------------------");
        String compressedString = compressString(originalString);
        System.out.println(compressedString);
        System.out.println("------------------------------------------------------");
        String uncompressedString = uncompressString(compressedString);
        System.out.println(uncompressedString);
        Validate.isTrue(originalString.equals(uncompressedString));
    }

    public static String compressString(String str) throws IOException {
        if (str == null || str.length() == 0) {
            return str;
        }
        byte[] bytes = str.getBytes(UTF_8);
        ByteArrayOutputStream out = new ByteArrayOutputStream(bytes.length);
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write(bytes);
        gzip.flush();
        gzip.close(); //Finalizes the ByteArrayOutputStream's value

        String compressedString = out.toString(UTF_8);
        return compressedString;
    }

    public static String uncompressString(String str) throws IOException {
        if (str == null || str.length() == 0) {
            return str;
        }
        ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes(UTF_8));
        GZIPInputStream gzip = new GZIPInputStream(in);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] b = new byte[1000];
        int len;
        while ((len = in.read(b)) > 0) {
            out.write(b, 0, len);
        }
        gzip.close();
        out.close();

        String uncompressedString = out.toString(UTF_8);
        return uncompressedString;
    }
}

0 个答案:

没有答案
相关问题