代码如下.
import (
“archive/zip”
“io”
“os”
“path/filepath”
“strings”
)
//zip压缩 srcFile 文件路径,destZip压缩包保存路径
func Zip(srcFile string, destZip string) error {
srcFiles := srcFile
zipfile, err := os.Create(destZip)
if err != nil {
return err
}
defer zipfile.Close()
archive := zip.NewWriter(zipfile)
defer archive.Close()
filepath.Walk(srcFile, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
path = strings.Replace(path, “\\”, “/”, -1)
srcFiles = strings.Replace(srcFiles, “\\”, “/”, -1)
header.Name = strings.Replace(path, srcFiles, “”, -1)
if info.IsDir() {
header.Name += “/”
} else {
header.Method = zip.Deflate
}
writer, err := archive.CreateHeader(header)
if err != nil {
return err
}
if !info.IsDir() {
var file *os.File
file, err = os.Open(path)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(writer, file)
}
return err
})
return err
}
//zip解压 zipFile 压缩包地址 destDir 解压保存文件夹
func Unzip(zipFile string, destDir string) error {
reader, err := zip.OpenReader(zipFile)
if err != nil {
return err
}
defer reader.Close()
dirLen := 0
for _, file := range reader.File {
if file.FileInfo().IsDir() {
err := os.MkdirAll(destDir+”/”+file.Name[dirLen:], 0755)
if err != nil {
return err
}
continue
} else {
srcFile, err := file.Open()
if err != nil {
return err
}
defer srcFile.Close()
destFile, err := os.Create(destDir + “/” + file.Name[dirLen:])
if err != nil {
return err
}
defer destFile.Close()
_, err = io.Copy(destFile, srcFile)
if err != nil {
return err
}
}
}
return nil
}
声明:
本文采用
BY-NC-SA
协议进行授权,如无注明均为原创,转载请注明转自
一颗大萝北
本文地址: GOLANG 打包ZIP与解压ZIP
本文地址: GOLANG 打包ZIP与解压ZIP