1. 程式人生 > 實用技巧 >Golang zip壓縮檔案讀寫操作

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