tar
最后更新于:2022-04-02 02:42:14
[TOC]
## tar
## 压缩 tar.gz
```
src:="parse"
dst:=fmt.Sprintf("%s.tar.gz",src)
dstFile, err := os.Create(dst)
if err != nil {
log.Fatal(err)
}
defer dstFile.Close()
gzipWrite := gzip.NewWriter(dstFile)
defer gzipWrite.Close()
handle := tar.NewWriter(gzipWrite)
defer handle.Close()
err = filepath.Walk("parser", func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
header, err := tar.FileInfoHeader(info, path)
if err != nil {
return err
}
// 保留层级关系
header.Name=strings.TrimPrefix(path,string(filepath.Separator))
if err = handle.WriteHeader(header);err != nil {
return err
}
if !info.Mode().IsRegular() {
return nil
}
openFile, err := os.Open(path)
if err != nil {
return err
}
_, err = io.Copy(handle, openFile)
if err != nil {
return err
}
return nil
})
```
## 解压 tar.gz
```
dstDir := "./"
tarFile, err := os.Open("parse.tar.gz")
if err != nil {
log.Fatal(err)
}
defer tarFile.Close()
gzipReader, err := gzip.NewReader(tarFile)
if err != nil {
log.Fatal(err)
}
tarReader := tar.NewReader(gzipReader)
for {
head, err := tarReader.Next()
if err != nil {
if errors.Is(err, io.EOF) {
os.Exit(0)
} else {
log.Fatal(err)
os.Exit(1)
}
}
dstFileDir := filepath.Join(dstDir, head.Name)
switch head.Typeflag {
case tar.TypeDir:
if err := os.MkdirAll(dstFileDir, 0755); err != nil {
log.Fatal(err)
}
case tar.TypeReg:
openFile, err := os.Create(dstFileDir)
if err != nil {
log.Fatal(err)
}
_, err = io.Copy(openFile, tarReader)
if err != nil {
log.Fatal(err)
}
openFile.Close()
}
}
```
';