Go实战--压缩zip和解压缩unzip的应用(The way to go)

来源:互联网 发布:新闻源软件 编辑:程序博客网 时间:2024/04/30 18:54

生命不止,继续 go go go !!!

今天跟大家介绍一下go中如何进行压缩和解压缩,先来点民间的,就就是比较通用的格式zip的压缩与解压缩。

archive/zip包
作用:
Package zip provides support for reading and writing ZIP archives.

func OpenReader

func OpenReader(name string) (*ReadCloser, error)

OpenReader will open the Zip file specified by name and return a ReadCloser.

func NewWriter

func NewWriter(w io.Writer) *Writer

NewWriter returns a new Writer writing a zip file to w.

os.MkdirAll
MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. The permission bits perm are used for all directories that MkdirAll creates. If path is already a directory, MkdirAll does nothing and returns nil.

os.OpenFile
OpenFile is the generalized open call; most users will use Open or Create instead. It opens the named file with specified flag (O_RDONLY etc.) and perm, (0666 etc.).

0666代表打开权限

bytes.Equal

func Equal(a, b []byte) bool

Equal returns a boolean reporting whether a and b are the same length and contain the same bytes. A nil argument is equivalent to an empty slice.

filepath.Join
Join joins any number of path elements into a single path, adding a Separator if necessary. Join calls Clean on the result; in particular, all empty strings are ignored. On Windows, the result is a UNC path if and only if the first path element is a UNC path.

例如:

package mainimport (    "fmt"    "path/filepath")func main() {    fmt.Println("On Unix:")    fmt.Println(filepath.Join("a", "b", "c"))    fmt.Println(filepath.Join("a", "b/c"))    fmt.Println(filepath.Join("a/b", "c"))    fmt.Println(filepath.Join("a/b", "/c"))}

判断是否是zip文件

package mainimport (    "bytes"    "fmt"    "os")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 main() {    result := isZip("1.zip")    fmt.Println(result)}

解压缩zip文件

package mainimport (    "archive/zip"    "bytes"    "fmt"    "io"    "os"    "path/filepath")func unzip(archive, target string) error {    reader, err := zip.OpenReader(archive)    if err != nil {        return err    }    if err := os.MkdirAll(target, 0755); err != nil {        return err    }    for _, file := range reader.File {        path := filepath.Join(target, file.Name)        if file.FileInfo().IsDir() {            os.MkdirAll(path, file.Mode())            continue        }        fileReader, err := file.Open()        if err != nil {            return err        }        defer fileReader.Close()        targetFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())        if err != nil {            return err        }        defer targetFile.Close()        if _, err := io.Copy(targetFile, fileReader); err != nil {            return err        }    }    return nil}func main() {    result := isZip("1.zip")    fmt.Println(result)    unzip("1.zip", "./")}

压缩成zip文件

package mainimport (    "archive/zip"    "bytes"    "log"    "os")func main() {    buf := new(bytes.Buffer)    w := zip.NewWriter(buf)    var files = []struct {        Name, Body string    }{        {"1.txt", "first"},        {"2.txt", "second"},        {"3.txt", "third"},    }    for _, file := range files {        f, err := w.Create(file.Name)        if err != nil {            log.Fatal(err)        }        _, err = f.Write([]byte(file.Body))        if err != nil {            log.Fatal(err)        }    }    err := w.Close()    if err != nil {        log.Fatal(err)    }    f, err := os.OpenFile("file.zip", os.O_CREATE|os.O_WRONLY, 0666)    if err != nil {        log.Fatal(err)    }    buf.WriteTo(f)}

这里写图片描述

1 0