golang1.5 tar.gz 打包目录,代码分享

前端之家收集整理的这篇文章主要介绍了golang1.5 tar.gz 打包目录,代码分享前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package main

import (
	"archive/tar"
	"compress/gzip"
	"fmt"
	"io"
	"io/IoUtil"
	"os"
	"strings"
)

func main() {
	fmt.Println(Gzip(".\\","1.tar.gz"))
}
func Gzip(filepath,filename string) error {
	File,err := os.Create(filename)
	if err != nil {
		return err
	}
	defer File.Close()
	gw := gzip.NewWriter(File)
	defer gw.Close()
	tw := tar.NewWriter(gw)
	defer tw.Close()

	return walk(filepath,tw)
}

func walk(path string,tw *tar.Writer) error {
	path = strings.Replace(path,"\\","/",-1)
	info,err := IoUtil.ReadDir(path)
	if err != nil {
		return err
	}
	if !strings.HasSuffix(path,"/") {
		path = path + "/"
	}
	index := strings.Index(path,"/")
	list := strings.Join(strings.Split(path,"/")[index:],"/")
	for _,v := range info {
		if v.IsDir() {
			head := tar.Header{Name: list + v.Name(),Typeflag: tar.TypeDir,ModTime: v.ModTime()}
			tw.WriteHeader(&head)
			walk(path+v.Name(),tw)
			continue
		}
		F,err := os.Open(path + v.Name())
		if err != nil {
			fmt.Println("打开文件%s失败.",err)
			continue
		}
		head := tar.Header{Name: list + v.Name(),Size: v.Size(),Mode: int64(v.Mode()),ModTime: v.ModTime()}
		tw.WriteHeader(&head)
		io.Copy(tw,F)
		F.Close()
	}
	return nil
}

猜你在找的Go相关文章