Golang zip压缩文件读写操作

创建zip文件

golang提供了archive/zip包来处理zip压缩文件,下面通过一个简单的示例来展示golang如何创建zip压缩文件:

func createZip(filename string) {
	// 缓存压缩文件内容
	buf := new(bytes.Buffer)

	// 创建zip
	writer := zip.NewWriter(buf)
	defer writer.Close()

	// 读取文件内容
	content, _ := ioutil.ReadFile(filepath.Clean(filename))

	// 接收
	f, _ := writer.Create(filename)
	f.Write(content)

	filename = strings.TrimSuffix(filename, path.Ext(filename)) + ".zip"
	ioutil.WriteFile(filename, buf.Bytes(), 0644)
}

读取zip文件

读取zip文档过程与创建zip文档过程类似,需要解压后的文档目录结构创建:

func readZip(filename string) {
      zipFile, err := zip.OpenReader(filename)
		if err != nil {
			panic(err.Error())
		}
		defer zipFile.Close()

		for _, f := range zipFile.File {
			info := f.FileInfo()
			if info.IsDir() {
				err = os.MkdirAll(f.Name, os.ModePerm)
				if err != nil {
					panic(err.Error())
				}
				continue
			}
			srcFile, err := f.Open()
			if err != nil {
				panic(err.Error())
			}
			defer srcFile.Close()

			newFile, err := os.Create( f.Name)
			if err != nil {
				panic(err.Error())
			}
			defer newFile.Close()

			io.Copy(newFile, srcFile)
		}
}
原文地址:https://www.cnblogs.com/lianshuiwuyi/p/14177568.html