go压缩解压zip文件源码示例
短信预约 -IT技能 免费直播动态提醒
压缩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 _, class="lazy" data-src := range paths {
// remove the trailing path sepeartor if it is a directory
class="lazy" data-src := strings.TrimSuffix(class="lazy" data-src, string(os.PathSeparator))
err = filepath.Walk(class="lazy" data-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(class="lazy" data-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(class="lazy" data-src string, dest string) error {
reader, err := zip.OpenReader(class="lazy" data-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文件源码示例的详细内容,更多关于go压缩解压zip文件的资料请关注编程网其它相关文章!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341