dsadsadsa1231 2014-07-26 15:01
浏览 57
已采纳

前往:zlib解压缩字节片

I am trying to parse a file that annoying consists of many separately zipped segments. I have parsed these segments one at a time into a slice of bytes and I want to uncompress them as I go.

Here is my current code that does the decompressing, which doesn't work. from and to are just set at the top as an example, in reality they are set by the code. data is the byte array containing the entire file. I don't want to seek it while it's on disk because its location on another server, so it's only realistic for me to load the entire file to []byte first and then parse it.

from, to := 0, 1000;
b := bytes.NewReader(data[from:from+to])
z, err := zlib.NewReader(b)
CheckErr(err)
defer z.Close()
p := make([]byte,0,1024)
z.Read(p)
fmt.Println(string(p))

So how is it so massively difficult just to unzip a slice of bytes? Anyway...

The problem appears to with how I am reading it out. Where it says z.Read, that doesn't seem to do anything.

How can I read the entire thing in one go into a slice of bytes?

  • 写回答

2条回答 默认 最新

  • douping3427 2014-07-26 15:32
    关注

    Here's an outline for you. Note: In Go, CHECK FOR ERRORS!

    package main
    
    import (
        "bytes"
        "compress/zlib"
        "fmt"
        "io/ioutil"
    )
    
    func readSegment(data []byte, from, to int) ([]byte, error) {
        b := bytes.NewReader(data[from : from+to])
        z, err := zlib.NewReader(b)
        if err != nil {
            return nil, err
        }
        defer z.Close()
        p, err := ioutil.ReadAll(z)
        if err != nil {
            return nil, err
        }
        return p, nil
    }
    
    func main() {
        from, to := 0, 1000
        data := make([]byte, from+to)
        // ** parse input segments into data **
        p, err := readSegment(data, from, to)
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Println(string(p))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作