如何使用golang的"compress/gzip"包来压缩文件?

pym*_*ymd 28 compression file-io gzip go

我是golang的新手,无法弄清楚如何使用golang的"compress/gzip"软件包.基本上,我只是想写一些文件,gzip并直接从压缩格式通过另一个脚本读取它.如果有人能给我一个如何做到这一点的例子我真的很感激.

lau*_*ent 47

所有压缩包都实现相同的接口.您可以使用这样的东西来压缩:

var b bytes.Buffer
w := gzip.NewWriter(&b)
w.Write([]byte("hello, world\n"))
w.Close()
Run Code Online (Sandbox Code Playgroud)

这打包:

r, err := gzip.NewReader(&b)
io.Copy(os.Stdout, r)
r.Close()
Run Code Online (Sandbox Code Playgroud)


Kev*_*ell 7

与Laurent几乎相同的答案,但使用文件io:

import (
  "bytes"
  "compress/gzip"
  "io/ioutil"
)
// ...
var b bytes.Buffer
w := gzip.NewWriter(&b)
w.Write([]byte("hello, world\n"))
w.Close() // You must close this first to flush the bytes to the buffer.
err := ioutil.WriteFile("hello_world.txt.gz", b.Bytes(), 0666)
Run Code Online (Sandbox Code Playgroud)

  • 您应该使用os.Open创建文件并将其传递给gzip.NewWriter,并且对该gzip writer的每次写入都会将压缩数据写入该文件. (4认同)

maz*_*res 7

对于阅读部分,像有用ioutil.ReadFile的.广州文件可以是:

func ReadGzFile(filename string) ([]byte, error) {
    fi, err := os.Open(filename)
    if err != nil {
        return nil, err
    }
    defer fi.Close()

    fz, err := gzip.NewReader(fi)
    if err != nil {
        return nil, err
    }
    defer fz.Close()

    s, err := ioutil.ReadAll(fz)
    if err != nil {
        return nil, err
    }
    return s, nil   
}
Run Code Online (Sandbox Code Playgroud)


Ole*_*kin 6

这里是将 gzip 文件解压到目标文件的函数:

func UnpackGzipFile(gzFilePath, dstFilePath string) (int64, error) {
    gzFile, err := os.Open(gzFilePath)
    if err != nil {
        return 0, fmt.Errorf("Failed to open file %s for unpack: %s", gzFilePath, err)
    }
    dstFile, err := os.OpenFile(dstFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660)
    if err != nil {
        return 0, fmt.Errorf("Failed to create destination file %s for unpack: %s", dstFilePath, err)
    }

    ioReader, ioWriter := io.Pipe()

    go func() { // goroutine leak is possible here
        gzReader, _ := gzip.NewReader(gzFile)
        // it is important to close the writer or reading from the other end of the
        // pipe or io.copy() will never finish
        defer func(){
            gzFile.Close()
            gzReader.Close()
            ioWriter.Close()
        }()

        io.Copy(ioWriter, gzReader)
    }()

    written, err := io.Copy(dstFile, ioReader)
    if err != nil {
        return 0, err // goroutine leak is possible here
    }
    ioReader.Close()
    dstFile.Close()

    return written, nil
}
Run Code Online (Sandbox Code Playgroud)