go怎么压缩和解压zip文件
本篇内容主要讲解“go怎么压缩和解压zip文件”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“go怎么压缩和解压zip文件”吧!
压缩zip
func Zip(dest string, paths ...string) error { zfile, err := os.Create(dest) if err != nil { return err } defer zfile.Close() zipWriter := zip.NewWriter(zfile) defer zipWriter.Close() for _, src := range paths { // remove the trailing path sepeartor if it is a directory src := strings.TrimSuffix(src, string(os.PathSeparator)) err = filepath.Walk(src, func(path string, info os.FileInfo, err error) error { if err != nil { return err } // create local file header header, err := zip.FileInfoHeader(info) if err != nil { return err } // set compression method to deflate header.Method = zip.Deflate // set relative path of file in zip archive header.Name, err = filepath.Rel(filepath.Dir(src), path) if err != nil { return err } if info.IsDir() { header.Name += string(os.PathSeparator) } // create writer for writing header headerWriter, err := zipWriter.CreateHeader(header) if err != nil { return err } if info.IsDir() { return nil } f, err := os.Open(path) if err != nil { return err } defer f.Close() _, err = io.Copy(headerWriter, f) return err }) if err != nil { return err } } return nil }
解压zip
func Unzip(src string, dest string) error { reader, err := zip.OpenReader(src) if err != nil { return err } defer reader.Close() for _, file := range reader.File { filePath := path.Join(dest, file.Name) if file.FileInfo().IsDir() { os.MkdirAll(filePath, os.ModePerm) } else { if err = os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil { return err } inFile, err := file.Open() if err != nil { return err } defer inFile.Close() outFile, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode()) if err != nil { return err } defer outFile.Close() _, err = io.Copy(outFile, inFile) if err != nil { return err } } } return nil }
到此,相信大家对“go怎么压缩和解压zip文件”有了更深的了解,不妨来实际操作一番吧!这里是蜗牛博客网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。版权声明:如无特殊标注,文章均为本站原创,转载时请以链接形式注明文章出处。
评论