go 壓縮解壓zip文件源碼示例
發(fā)布日期:2022-07-15 19:09 | 文章來源:CSDN
壓縮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 }
工程源碼
https://github.com/xbmlz/gct
以上就是go 壓縮解壓zip文件源碼示例的詳細(xì)內(nèi)容,更多關(guān)于go壓縮解壓zip文件的資料請(qǐng)關(guān)注本站其它相關(guān)文章!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
相關(guān)文章