在Go中压缩一个字节数组 [英] Zip a byte array in Go

查看:85
本文介绍了在Go中压缩一个字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取大量字节,并使用Go中的 archive/zip 包对其进行压缩.但是,我一点也不明白.是否有任何示例可以说明如何做到这一点,并且对该隐秘软件包有任何解释吗?

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?

推荐答案

感谢jamessan,我确实找到了示例(它并不完全引起您的注意).

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

这就是我想出的结果:

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)    

}

我希望您觉得它有用:)

I hope you find it useful :)

这篇关于在Go中压缩一个字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆