zip

最后更新于:2022-04-02 02:42:16

[TOC] ## 压缩 ``` src:="xrpc" dst:=fmt.Sprintf("%s.zip",src) dstFile, err := os.Create(dst) if err != nil { log.Fatal(err) } defer dstFile.Close() handle := zip.NewWriter(dstFile) defer handle.Close() err = filepath.Walk(src, func(path string, info os.FileInfo, err error) error { if err != nil { return err } header, err := zip.FileInfoHeader(info) if err != nil { return err } // 保留层级关系 header.Name=strings.TrimPrefix(path,string(filepath.Separator)) wh, err := handle.CreateHeader(header) if err != nil { return err } if !info.Mode().IsRegular() { return nil } openFile, err := os.Open(path) if err != nil { return err } _, err = io.Copy(wh, openFile) if err != nil { return err } return nil }) ``` ## 解压 ``` dstDir := "./" zipReader, err := zip.OpenReader("xrpc.zip") if err != nil { log.Fatal(err) } defer zipReader.Close() for _, file := range zipReader.File { realPath := filepath.Join(dstDir,file.Name) if file.Mode().IsDir(){ err := os.MkdirAll(realPath, os.ModePerm) if err != nil { log.Fatal(err) } }else{ create, err := os.Create(realPath) if err != nil { log.Fatal(err) } open, err := file.Open() if err != nil { log.Fatal(err) } _, err = io.Copy(create, open) if err != nil { log.Fatal(err) } } } ```
';