英文:
Zip a byte array in Go
问题
我正在尝试使用Go语言中的<code>archive/zip</code>包来压缩一段字节。然而,我完全不理解它。是否有任何示例可以演示如何完成这个任务,并且有没有对这个神秘的包进行解释的文档?
英文:
I am trying to take a chunk of bytes and compress them using the <code>archive/zip</code> 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
得分: 28
感谢jamessan,我找到了这个例子(它并不特别引人注目)。
这是我得出的结果:
func (this *Zipnik) zipData() {
// 创建一个缓冲区来写入我们的归档文件。
fmt.Println("我们在zipData函数中")
buf := new(bytes.Buffer)
// 创建一个新的zip归档文件。
zipWriter := zip.NewWriter(buf)
// 向归档文件中添加一些文件。
var files = []struct {
Name, Body string
}{
{"readme.txt", "这个归档文件包含一些文本文件。"},
{"gopher.txt", "Gopher的名字:\nGeorge\nGeoffrey\nGonzo"},
{"todo.txt", "获取动物处理许可证。\n编写更多示例。"},
}
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)
}
}
// 确保在关闭时检查错误。
err := zipWriter.Close()
if err != nil {
fmt.Println(err)
}
// 将压缩文件写入磁盘
ioutil.WriteFile("Hello.zip", buf.Bytes(), 0777)
}
希望你觉得有用
英文:
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:\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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论