在 Go 中压缩一个字节数组

标签 zip go

我正在尝试获取一大块字节并使用 Go 中的 archive/zip 包压缩它们。然而,我根本看不懂。是否有关于如何完成的示例,是否有关于该神秘包的任何解释?

最佳答案

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

}

希望你觉得它有用:)

关于在 Go 中压缩一个字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12440387/

相关文章:

java - 热衷于使用 Play 创建 zip 文件!框架?

gradle - Gradle 中的 Zip 依赖项

go - Golang 中的模糊字符串匹配

arrays - 在Go中,如何确定数组中 slice 的偏移量?

session - session 实现中的注册表

html - 在 Go 中解析数组后表单数据

go - 工作池实现以限制每秒的 http 请求

groovy - 如何在不使用 ant 的情况下在 groovy 中压缩文件?

php - 提取下载的 zip 文件的内容而不将其存储到 PHP 中的光盘

zip - 尝试在命令行中静默执行自解压 zip 文件