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条)

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题