1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
zip.go 2.06 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2022-11-01 20:57 . 上传文件调整
package compress
import (
"archive/zip"
"bytes"
"gitee.com/h79/goutils/common/logger"
"io"
"os"
"path/filepath"
"strings"
)
func IsZip(zipPath string) bool {
f, err := os.Open(zipPath)
if err != nil {
return false
}
defer f.Close()
buf := make([]byte, 4)
if n, err := f.Read(buf); err != nil || n < 4 {
return false
}
return bytes.Equal(buf, []byte("PK\x03\x04"))
}
func UNZipFile(archive, target string) error {
reader, err := zip.OpenReader(archive)
if err != nil {
return err
}
defer reader.Close()
var er error = nil
for _, file := range reader.File {
path := filepath.Join(target, file.Name)
if file.FileInfo().IsDir() {
_ = os.MkdirAll(path, file.Mode())
continue
}
fileReader, err0 := file.Open()
if err0 != nil {
er = err0
break
}
targetFile, err1 := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())
if err1 != nil {
er = err1
_ = fileReader.Close()
break
}
if _, err2 := io.Copy(targetFile, fileReader); err2 != nil {
er = err2
_ = targetFile.Close()
_ = fileReader.Close()
break
}
_ = targetFile.Close()
_ = fileReader.Close()
}
return er
}
func ZipFile(srcPath, destPath string) error {
zipFile, err := os.Create(destPath)
if err != nil {
return err
}
defer zipFile.Close()
archive := zip.NewWriter(zipFile)
defer func() {
if err = archive.Close(); err != nil {
logger.Fatal("error closing zip archive: %v", err)
}
}()
return filepath.Walk(srcPath, func(path string, info os.FileInfo, _ error) error {
if path == srcPath {
return nil
}
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
header.Name = strings.TrimPrefix(path, srcPath+`/`)
if info.IsDir() {
header.Name += `/`
} else {
header.Method = zip.Deflate
}
writer, err := archive.CreateHeader(header)
if err != nil {
return err
}
if !info.IsDir() {
file, err := os.Open(path)
if err != nil {
return err
}
if _, err := io.Copy(writer, file); err != nil {
file.Close()
return err
}
file.Close()
}
return nil
})
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.2.10

搜索帮助