【问题标题】:Zip a byte array in Go在 Go 中压缩一个字节数组
【发布时间】:2012-09-08 13:19:42
【问题描述】:

我正在尝试获取一大块字节并使用 Go 中的 archive/zip 包压缩它们。但是,我完全无法理解。有没有什么例子可以说明它是如何完成的?有没有对那个神秘包的解释?

【问题讨论】:

  • 包的文档中有一个例子——golang.org/pkg/archive/zip/#example_Writer
  • 因“这个问题没有显示任何研究工作”而被否决。请告诉我们您尝试了什么,和/或您使用了哪些参考资料(例如官方 zip 包,您尝试过的功能似乎匹配但不起作用)。
  • @Kissaki 在学习一门新的计算机语言时,首先要克服的障碍之一就是理解文档。我花了很多精力试图理解它,并编写了一些根本没有任何意义的代码。最后一根稻草是我找到了一篇关于 zip 包的文章,上面写着“write() 方法已从 Writer 中删除,因为放在那里出错了”。这完全让我大吃一惊,我转向 Stackoverflow。

标签: zip go


【解决方案1】:

感谢 jamessan,我确实找到了这个例子(它并没有完全引起你的注意)。

这是我想出的结果:

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:\nGeorge\nGeoffrey\nGonzo"},
        {"todo.txt", "Get animal handling licence.\nWrite 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)    

}

我希望你觉得它有用:)

【讨论】:

  • 您可以接受自己的答案。它可以帮助其他人看到问题得到了您满意的解决。
  • 如何围绕这个编写测试?您如何从为 zip 创建的缓冲区中读取数据?
  • 嗨,如果您的意思是在调用 zip 之前从字节数组转换为字符串,这会告诉您 stackoverflow.com/questions/14230145/…。上面看起来只是将字符串内容放入 ZIP。
猜你喜欢
  • 2018-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-24
  • 1970-01-01
相关资源
最近更新 更多