繁体   English   中英

Java字节数组压缩

[英]Java byte array compression

我正在尝试使用Java DeflaterOutputStreamInflaterOutputStream类来压缩字节数组,但两者似乎均无法正常工作。 我认为我没有正确实现它们。

public static byte[] compress(byte[] in) {
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DeflaterOutputStream defl = new DeflaterOutputStream(out);
        defl.write(in);
        defl.flush();
        defl.close();

        return out.toByteArray();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(150);
        return null;
    }
}

public static byte[] decompress(byte[] in) {
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        InflaterOutputStream infl = new InflaterOutputStream(out);
        infl.write(in);
        infl.flush();
        infl.close();

        return out.toByteArray();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(150);
        return null;
    }
}

这是我用来压缩和解压缩字节数组的两种方法。 我在网上看到的大多数实现都在减压部分使用了固定大小的缓冲区数组,但如果可能的话,我宁愿避免这种情况,因为如果我想使用任何大小的缓冲区数组,都需要使该缓冲区数组的大小为1。显着压缩。

如果有人可以向我解释我在做什么错,将不胜感激。 另外,要解释为什么我知道这些方法不能正常工作:无论我尝试提供哪种大小的字节数组,它输出的“压缩”字节数组总是大于未压缩的字节数组。

压缩总是有开销,以允许将来进行解压缩。 如果压缩没有减少长度(数据是唯一的或几乎唯一的),则输出文件可能比输入文件长

这将取决于您要压缩的数据。 例如,如果我们采用一个0字节的数组,则压缩效果很好:

byte[] plain = new byte[10000];
byte[] compressed = compress(plain);
System.out.println(compressed.length); // 33
byte[] result = decompress(compressed);
System.out.println(result.length); // 10000

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM