在Go中压缩字节数组

huangapple go评论83阅读模式
英文:

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)	
	
}

希望你觉得有用 在Go中压缩字节数组

英文:

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(&quot;we are in the zipData function&quot;)
	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
	}{
		{&quot;readme.txt&quot;, &quot;This archive contains some text files.&quot;},
		{&quot;gopher.txt&quot;, &quot;Gopher names:\nGeorge\nGeoffrey\nGonzo&quot;},
		{&quot;todo.txt&quot;, &quot;Get animal handling licence.\nWrite more examples.&quot;},
	}
	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(&quot;Hello.zip&quot;, buf.Bytes(), 0777)	
	
}

I hope you find it useful 在Go中压缩字节数组

huangapple
  • 本文由 发表于 2012年9月16日 03:40:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/12440387.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定