java - Php在Java中的gzcompress

标签 java php compression gzip

我尝试像 php 的 gzcompress 函数那样在 Java 中压缩字符串。但我无法在结果中获得相同的字节数组。

我的 php 代码:

<?php
echo 'This is a test';
$compressed = gzcompress('This is a test');
echo '<br>';
for ($i=0; $i<strlen($compressed); $i++) {
    echo '['.$i.'] = '.ord($compressed[$i]).'<br>';
}
?>

结果:

这是一个测试

[0] = 120 
[1] = 156 
[2] = 11 
[3] = 201 
[4] = 200 
[5] = 44 
[6] = 86 
[7] = 0 
[8] = 162 
[9] = 68 
[10] = 133 
[11] = 146 
[12] = 212 
[13] = 226 
[14] = 18 
[15] = 0 
[16] = 36 
[17] = 115 
[18] = 4 
[19] = 246 

Java代码:

public class Main {

    public static byte[] compressString(String uncompressedString) throws IllegalArgumentException, IllegalStateException {
        try {
            byte[] utfEncodedBytes = uncompressedString.getBytes();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(baos)) {
                gzipOutputStream.write(utfEncodedBytes);
                gzipOutputStream.finish();
            }
            return baos.toByteArray();
        } catch (Exception e) {
            throw new IllegalStateException("GZIP compression failed: " + e, e);
        }
    }

    public static void main(String[] args) {
        String input = "This is a test";
        System.out.println("Input:  " + input);
        byte[] compressed = compressString(input);
        for (int i = 0; i < compressed.length; i++) {
            System.out.println("[" + i + "] = " + (compressed[i] & 0xFF));
        }
    }
}

结果:

输入:这是一个测试

[0] = 31 
[1] = 139 
[2] = 8 
[3] = 0 
[4] = 0 
[5] = 0 
[6] = 0 
[7] = 0 
[8] = 0 
[9] = 0 
[10] = 11 
[11] = 201 
[12] = 200 
[13] = 44 
[14] = 86 
[15] = 0 
[16] = 162 
[17] = 68 
[18] = 133 
[19] = 146 
[20] = 212 
[21] = 226 
[22] = 18 
[23] = 0 
[24] = 50 
[25] = 159 
[26] = 122 
[27] = 192 
[28] = 14
[29] = 0 
[30] = 0 
[31] = 0 

压缩数组的中间部分是相同的。但他们的开始和结束是不同的。

最佳答案

documentation for the gzcompress function特别说明它使用的压缩算法是zlib,也就是

not the same as gzip compression, which includes some header data. See gzencode() for gzip compression.

Java 的 GZIPOutputStream 进行适当的 gzip 压缩,包括正确的 header 。 DeflaterOutputStream 确实在没有 gzip header 的情况下进行普通压缩,这可能更接近您所追求的,或者有第三方解决方案,例如 JZlib .

关于java - Php在Java中的gzcompress,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12128944/

相关文章:

java - 映射以在 Dozer 中设置映射解决方法

java - 如何使用spring访问外部jar文件中的资源?

php - Heroku PHP 立即消耗所有内存

php - 使用 AJAX 和 Codeigniter 从数据库中删除用户

php - 我什么时候可以开始使用框架 (Laravel)?

c - 解释lz4双缓冲示例

algorithm - 反向 "jpeg"压缩算法?

java - NavigationDrawerActivity 和 BottomNavigationActivity

java - Eclipse 内存分析器 - 尝试获取堆转储时出错

java - 如何在没有任何 for 循环的情况下递归地解压缩字符串?