1

期望:
创建压缩和解压缩字符串或字节数组。之后,我计划对它进行 Base64 编码以写入日志文件。

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

输出: 在此处输入图像描述

测试类:

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;
    }
}
4

0 回答 0