在Go中压缩一个字节数组

时间:2012-09-15 19:40:51

标签: zip go

我正在尝试获取一大块字节并使用Go中的archive/zip包压缩它们。但是,我根本无法理解。有没有关于如何做到这一点的例子,是否对这个神秘的包裹有任何解释?

1 个答案:

答案 0 :(得分:11)

感谢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)    

}

我希望你觉得它很有用:)

相关问题