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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM