简体   繁体   English

Java字节数组压缩

[英]Java byte array compression

I'm trying to use the java DeflaterOutputStream and InflaterOutputStream classes to compress a byte array, but both appear to not be working correctly. 我正在尝试使用Java DeflaterOutputStreamInflaterOutputStream类来压缩字节数组,但两者似乎均无法正常工作。 I assume I'm incorrectly implementing them. 我认为我没有正确实现它们。

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

Here's the two methods I'm using to compress and decompress the byte array. 这是我用来压缩和解压缩字节数组的两种方法。 Most implementations I've seen online use a fixed size buffer array for the decompression portion, but I'd prefer to avoid that if possible, because I'd need to make that buffer array have a size of one if I want to have any significant compression. 我在网上看到的大多数实现都在减压部分使用了固定大小的缓冲区数组,但如果可能的话,我宁愿避免这种情况,因为如果我想使用任何大小的缓冲区数组,都需要使该缓冲区数组的大小为1。显着压缩。

If anyone can explain to me what I'm doing wrong it would be appreciated. 如果有人可以向我解释我在做什么错,将不胜感激。 Also, to explain why I know these methods aren't working correctly: The "compressed" byte array that it outputs is always larger than the uncompressed one, no matter what size byte array I attempt to provide it. 另外,要解释为什么我知道这些方法不能正常工作:无论我尝试提供哪种大小的字节数组,它输出的“压缩”字节数组总是大于未压缩的字节数组。

Compression always has overhead to allow for future decompression. 压缩总是有开销,以允许将来进行解压缩。 If the compression produced no reduction in length (the data was unique or nearly unique) then the output file could be longer than the input file 如果压缩没有减少长度(数据是唯一的或几乎唯一的),则输出文件可能比输入文件长

This will depend on the data you are compressing. 这将取决于您要压缩的数据。 For example if we take an array of 0 bytes it compresses well: 例如,如果我们采用一个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