猿问

为什么Java和Go的gzip得到不同的结果?

首先,我的Java版本:


string str = "helloworld";

ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream(str.length());

GZIPOutputStream localGZIPOutputStream = new GZIPOutputStream(localByteArrayOutputStream);

localGZIPOutputStream.write(str.getBytes("UTF-8"));

localGZIPOutputStream.close();

localByteArrayOutputStream.close();

for(int i = 0;i < localByteArrayOutputStream.toByteArray().length;i ++){

    System.out.println(localByteArrayOutputStream.toByteArray()[i]);

}

和输出是:


31 -117 8 0 0 0 0 0 0 0 -53 72 -51 -55 -55 47 -49 47 -54 73 1 0 -83 32 -21 -7 10 0 0 0


然后是 Go 版本:


var gzBf bytes.Buffer

gzSizeBf := bufio.NewWriterSize(&gzBf, len(str))

gz := gzip.NewWriter(gzSizeBf)

gz.Write([]byte(str))

gz.Flush()

gz.Close()

gzSizeBf.Flush()

GB := (&gzBf).Bytes()

for i := 0; i < len(GB); i++ {

    fmt.Println(GB[i])

}

输出:


31 139 8 0 0 9 110 136 0 255 202 72 205 201 201 47 207 47 202 73 1 0 0 0 255 255 1 0 0 255 253 2 0 4 0


为什么?


一开始我以为可能是这两种语言的字节读取方式不同造成的。但是我注意到 0 永远不能转换为 9。而且 的大小[]byte不同。


我写错了代码吗?有什么办法可以让我的 Go 程序得到与 Java 程序相同的输出?


一只萌萌小番薯
浏览 245回答 2
2回答

郎朗坤

从RFC 1952 开始,GZip 文件头的结构如下:+---+---+---+---+---+---+---+---+---+---+|ID1|ID2|CM |FLG|&nbsp; &nbsp; &nbsp;MTIME&nbsp; &nbsp; &nbsp;|XFL|OS | (more-->)+---+---+---+---+---+---+---+---+---+---+查看您提供的输出,我们有:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; |&nbsp; &nbsp; Java |&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; GoID1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;|&nbsp; &nbsp; &nbsp; 31 |&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 31ID2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;|&nbsp; &nbsp; &nbsp;139 |&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;139CM (compression method)&nbsp; &nbsp;|&nbsp; &nbsp; &nbsp; &nbsp;8 |&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;8FLG (flags)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;|&nbsp; &nbsp; &nbsp; &nbsp;0 |&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0MTIME (modification time) | 0 0 0 0 | 0 9 110 136XFL (extra flags)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;|&nbsp; &nbsp; &nbsp; &nbsp;0 |&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0OS (operating system)&nbsp; &nbsp; &nbsp;|&nbsp; &nbsp; &nbsp; &nbsp;0 |&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;255所以我们可以看到,Go 正在设置头部的修改时间字段,并将操作系统设置为255(未知)而不是0(FAT 文件系统)。在其他方面,它们表明文件以相同的方式压缩。一般来说,这些类型的差异是无害的。如果您想确定两个压缩文件是否相同,那么您应该真正比较文件的解压缩版本。
随时随地看视频慕课网APP

相关分类

Go
我要回答