dongmeiwei0226 2012-09-15 19:40
浏览 130
已采纳

在Go中压缩一个字节数组

I am trying to take a chunk of bytes and compress them using the archive/zip package in Go. However, I can't understand it at all. Are there any examples of how it could be done and is there any explanation of that cryptic package?

  • 写回答

1条回答 默认 最新

  • duanjihe5180 2012-09-16 11:28
    关注

    Thanks to jamessan I did find the example (which doesn't exactly catch your eye).

    Here is what I come up with as the result:

    func (this *Zipnik) zipData() {
    
        // Create a buffer to write our archive to.
        fmt.Println("we are in the zipData function")
        buf := new(bytes.Buffer)
    
        // Create a new zip archive.
        zipWriter := zip.NewWriter(buf)
    
        // Add some files to the archive.
        var files = []struct {
            Name, Body string
        }{
            {"readme.txt", "This archive contains some text files."},
            {"gopher.txt", "Gopher names:
    George
    Geoffrey
    Gonzo"},
            {"todo.txt", "Get animal handling licence.
    Write more examples."},
        }
        for _, file := range files {
        zipFile, err := zipWriter.Create(file.Name)
            if err != nil {
                fmt.Println(err)
            }
            _, err = zipFile.Write([]byte(file.Body))  
            if err != nil {
                fmt.Println(err)
            }
        }
    
        // Make sure to check the error on Close.
        err := zipWriter.Close()
        if err != nil {
            fmt.Println(err)
        }
    
        //write the zipped file to the disk
        ioutil.WriteFile("Hello.zip", buf.Bytes(), 0777)    
    
    }
    

    I hope you find it useful :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何实验stm32主通道和互补通道独立输出
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题