Create Zip with java program and while unzip using Golang, getting issue as "zlib: invalid header"

huangapple go评论96阅读模式
英文:

Create Zip with java program and while unzip using Golang, getting issue as "zlib: invalid header"

问题

我正在使用两个应用程序,一个是用Java编写的,需要对字符串数据进行压缩,另一个是用Golang编写的,需要解压第一个应用程序压缩的记录。

Java程序创建字符串数据的压缩文件

public static byte[] createZipForLicenses(String string) throws UnsupportedEncodingException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
    zipOutputStream.setLevel(Deflater.DEFAULT_COMPRESSION);

    try {
        if (string != null && string.length() > 0) {
            ZipEntry zipEntry = new ZipEntry("data");
            zipOutputStream.putNextEntry(zipEntry);
            zipOutputStream.write(string.getBytes("UTF-8"));
            zipOutputStream.closeEntry();
        }

        zipOutputStream.close();
    } catch (IOException e) {
        // 处理异常
    }
    return outputStream.toByteArray();
}

Golang程序解压字符串数据

func Unzip(data []byte) (string, error) {
    rdata := bytes.NewReader(data)
    r, err := zlib.NewReader(rdata) // 错误 -> "zlib: invalid header"
    if err != nil {
        return "", err
    }
    s, err := io.ReadAll(r)
    if err != nil {
        return "", err
    }
    return string(s), nil
}

我尝试使用compress/flate库,但是出现错误"flate: corrupt input before offset 5"。

英文:

I am having two application one written in java where required to zip string of data and other in golang and required to unzip the record zipped by first application

Java program to Creating Zipped of string data

public static byte[] createZipForLicenses(String string) throws UnsupportedEncodingException {
	ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
	zipOutputStream.setLevel(Deflater.DEFAULT_COMPRESSION);

	try {

		if (string != null && string.length() > 0) {
			ZipEntry zipEntry = new ZipEntry("data");
			zipOutputStream.putNextEntry(zipEntry);
			zipOutputStream.write(string.getBytes("UTF-8"));
			zipOutputStream.closeEntry();
		}

		zipOutputStream.close();

	} catch (IOException e) {

	}
	return outputStream.toByteArray();
}

Golang program to unzip the string data

func Unzip(data []byte) (string, error) {

rdata := bytes.NewReader(data)
r, err := zlib.NewReader(rdata) //**Error**-> "zlib: invalid header	
if err != nil {
	return "", err
}
s, err := io.ReadAll(r)
if err != nil {
	return "", err
}
return string(s), nil

}

I tried using compress/flate lib also but with this getting error "flate: corrupt input before offset 5"

答案1

得分: 1

func Unzip(data []byte) (string, error) {
zipReader, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
panic(err)
}
if len(zipReader.File) == 0 {
return "", nil // 没有要打开/提取的文件
}
f, err := zipReader.File[0].Open()
if err != nil {
panic(err)
}
p, err := ioutil.ReadAll(f)
if err != nil {
return "", err
}
return string(p), nil

}

英文:
func Unzip(data []byte) (string, error) {
zipReader, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
	panic(err)
}
if len(zipReader.File) == 0 {
	return "", nil // No file to open / extract
}
f, err := zipReader.File[0].Open()
if err != nil {
	panic(err)
}
p, err := ioutil.ReadAll(f)
if err != nil {
	return "", err
}
return string(p), nil

}

答案2

得分: -1

Java部分看起来很好:

public static byte[] createZipForLicenses(String string) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ZipOutputStream zipOutputStream = new ZipOutputStream(out);
    zipOutputStream.setLevel(Deflater.DEFAULT_COMPRESSION);

    if (string != null && string.length() > 0) {
        ZipEntry zipEntry = new ZipEntry("data");
        zipOutputStream.putNextEntry(zipEntry);
        zipOutputStream.write(string.getBytes("UTF-8"));
        zipOutputStream.closeEntry();
    }

    zipOutputStream.close();

    return out.toByteArray();
}

我能够使用WinZip读取这个zip文件。以下是zip文件的信息:

(PK0506) 中央目录记录结束
========================================
    - 位置:116 (0x00000074) 字节
    - 大小:22 字节
    本部分的部分编号 (0000):1
    中央目录开始的部分编号 (0000):1
    本部分中的中央目录条目数:1
    中央目录中的总条目数:1
    中央目录的大小:50 (0x00000032) 字节
    中央目录的相对偏移量:66 (0x00000042) 字节
    zip文件注释长度:0 字节

(PK0102) 中央目录
==========================
    - 位置:66 (0x00000042) 字节
    - 大小:54 字节
    总条目数:1

#1 (PK0102) [UTF-8] data
------------------------
    - 位置:66 (0x00000042) 字节
    - 大小:50 字节
    本部分的部分编号 (0000):1
    本地头的相对偏移量:0 (0x00000000) 字节
    由操作系统生成的版本 (00):MS-DOS、OS/2、NT FAT
    由zip软件生成的版本 (20):2.0
    解压所需的操作系统版本 (00):MS-DOS、OS/2、NT FAT
    解压所需的解压软件版本 (20):2.0
    通用目的位标志 (0x0808) (位 15..0):0000.1000 0000.1000
      文件安全状态 (位 0):未加密
      数据描述符 (位 3):是
      强加密 (位 6):否
      UTF-8名称 (位 11):是
    压缩方法 (08):deflated
      压缩子类型 (deflation):normal
    文件最后修改时间 (0x5563 0x542A):2022-11-03 10:33:20
    32位CRC值:0x373555E7
    压缩大小:16 字节
    未压缩大小:14 字节
    文件名长度:4
                UTF-8
    64 61 74 61     data
    文件注释长度:0 字节
    内部文件属性:0x0000
      显式文件类型:二进制
    外部文件属性:0x00000000
      WINDOWS (0x00):无
      POSIX (0x000000):?---------

(PK0304) ZIP条目
====================
    总条目数:1

#1 (PK0304) [UTF-8] data
------------------------
    - 位置:0 (0x00000000) 字节
    - 大小:34 字节
    解压所需的操作系统版本 (00):MS-DOS、OS/2、NT FAT
    解压所需的解压软件版本 (20):2.0
    通用目的位标志 (0x0808) (位 15..0):0000.1000 0000.1000
      文件安全状态 (位 0):未加密
      数据描述符 (位 3):是
      强加密 (位 6):否
      UTF-8名称 (位 11):是
    压缩方法 (08):deflated
      压缩子类型 (deflation):normal
    文件最后修改时间 (0x5563 0x542A):2022-11-03 10:33:20
    32位CRC值:0x00000000
    压缩大小:0 字节
    未压缩大小:0 字节
    文件名长度:4
                UTF-8
    64 61 74 61     data

#1 (PK0708) 数据描述符
---------------------------
    - 位置:50 (0x00000032) 字节
    - 大小:16 字节
    32位CRC值:0x373555E7
    压缩大小:16 字节
    未压缩大小:14 字节

看起来你用Go解压时出现了错误。

P.S. 为了在Java中避免大量的代码来压缩/解压文件,你可以使用zip4jvm

英文:

Java part looks good to me:

public static byte[] createZipForLicenses(String string) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ZipOutputStream zipOutputStream = new ZipOutputStream(out);
    zipOutputStream.setLevel(Deflater.DEFAULT_COMPRESSION);

    if (string != null && string.length() > 0) {
        ZipEntry zipEntry = new ZipEntry("data");
        zipOutputStream.putNextEntry(zipEntry);
        zipOutputStream.write(string.getBytes("UTF-8"));
        zipOutputStream.closeEntry();
    }

    zipOutputStream.close();

    return out.toByteArray();
}

And am able to read this zip with WinZip. And this is a zip info:

(PK0506) End of Central directory record
========================================
    - location:                                     116 (0x00000074) bytes
    - size:                                         22 bytes
    part number of this part (0000):                1
    part number of start of central dir (0000):     1
    number of entries in central dir in this part:  1
    total number of entries in central dir:         1
    size of central dir:                            50 (0x00000032) bytes
    relative offset of central dir:                 66 (0x00000042) bytes
    zipfile comment length:                         0 bytes

(PK0102) Central directory
==========================
    - location:                                     66 (0x00000042) bytes
    - size:                                         54 bytes
    total entries:                                  1

#1 (PK0102) [UTF-8] data
------------------------
    - location:                                     66 (0x00000042) bytes
    - size:                                         50 bytes
    part number of this part (0000):                1
    relative offset of local header:                0 (0x00000000) bytes
    version made by operating system (00):          MS-DOS, OS/2, NT FAT
    version made by zip software (20):              2.0
    operat. system version needed to extract (00):  MS-DOS, OS/2, NT FAT
    unzip software version needed to extract (20):  2.0
    general purpose bit flag (0x0808) (bit 15..0):  0000.1000 0000.1000
      file security status  (bit 0):                not encrypted
      data descriptor       (bit 3):                yes
      strong encryption     (bit 6):                no
      UTF-8 names          (bit 11):                yes
    compression method (08):                        deflated
      compression sub-type (deflation):             normal
    file last modified on (0x5563 0x542A):          2022-11-03 10:33:20
    32-bit CRC value:                               0x373555E7
    compressed size:                                16 bytes
    uncompressed size:                              14 bytes
    length of filename:                             4
                                                    UTF-8
    64 61 74 61                                     data
    length of file comment:                         0 bytes
    internal file attributes:                       0x0000
      apparent file type:                           binary
    external file attributes:                       0x00000000
      WINDOWS   (0x00):                             none
      POSIX (0x000000):                             ?---------

(PK0304) ZIP entries
====================
    total entries:                                  1

#1 (PK0304) [UTF-8] data
------------------------
    - location:                                     0 (0x00000000) bytes
    - size:                                         34 bytes
    operat. system version needed to extract (00):  MS-DOS, OS/2, NT FAT
    unzip software version needed to extract (20):  2.0
    general purpose bit flag (0x0808) (bit 15..0):  0000.1000 0000.1000
      file security status  (bit 0):                not encrypted
      data descriptor       (bit 3):                yes
      strong encryption     (bit 6):                no
      UTF-8 names          (bit 11):                yes
    compression method (08):                        deflated
      compression sub-type (deflation):             normal
    file last modified on (0x5563 0x542A):          2022-11-03 10:33:20
    32-bit CRC value:                               0x00000000
    compressed size:                                0 bytes
    uncompressed size:                              0 bytes
    length of filename:                             4
                                                    UTF-8
    64 61 74 61                                     data

#1 (PK0708) Data descriptor
---------------------------
    - location:                                     50 (0x00000032) bytes
    - size:                                         16 bytes
    32-bit CRC value:                               0x373555E7
    compressed size:                                16 bytes
    uncompressed size:                              14 bytes

Looks like you unzip it with Go incorrectly.

P.S. To avoid a lot of code when zip/unzip files in java, you can use zip4jvm

huangapple
  • 本文由 发表于 2022年11月3日 15:19:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/74299267.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定