Go语言 如何使用“compress/gzip”包来gzip文件?

ykejflvf  于 2022-12-07  发布在  Go
关注(0)|答案(6)|浏览(149)

我是Go新手,不知道如何使用compress/gzip包。基本上,我只想写一些东西到一个文件,gzip它,并通过另一个脚本直接从压缩的格式读取它。如果有人能给予我一个如何做的例子,我会非常感激。

0sgqnhkj

0sgqnhkj1#

所有的压缩包都实现了相同的接口。

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

还有这个要打开

r, err := gzip.NewReader(&b)
io.Copy(os.Stdout, r)
r.Close()
carvr3hs

carvr3hs2#

答案和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)
rks48beu

rks48beu3#

对于读取部分,类似于**.gz**文件的有用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   
}
xfb7svmp

xfb7svmp4#

下面是将gzip文件解压缩到目标文件的函数:

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

    ioReader, ioWriter := io.Pipe()
    defer ioReader.Close()

    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
    }

    return written, nil
}
b1payxdu

b1payxdu5#

我决定合并其他人的想法和答案,只是提供一个完整的例子程序。显然有很多不同的方法来做同样的事情。这只是一种方法:

package main

import (
    "compress/gzip"
    "fmt"
    "io/ioutil"
    "os"
)

var zipFile = "zipfile.gz"

func main() {
    writeZip()
    readZip()
}

func writeZip() {
    handle, err := openFile(zipFile)
    if err != nil {
        fmt.Println("[ERROR] Opening file:", err)
    }

    zipWriter, err := gzip.NewWriterLevel(handle, 9)
    if err != nil {
        fmt.Println("[ERROR] New gzip writer:", err)
    }
    numberOfBytesWritten, err := zipWriter.Write([]byte("Hello, World!\n"))
    if err != nil {
        fmt.Println("[ERROR] Writing:", err)
    }
    err = zipWriter.Close()
    if err != nil {
        fmt.Println("[ERROR] Closing zip writer:", err)
    }
    fmt.Println("[INFO] Number of bytes written:", numberOfBytesWritten)

    closeFile(handle)
}

func readZip() {
    handle, err := openFile(zipFile)
    if err != nil {
        fmt.Println("[ERROR] Opening file:", err)
    }

    zipReader, err := gzip.NewReader(handle)
    if err != nil {
        fmt.Println("[ERROR] New gzip reader:", err)
    }
    defer zipReader.Close()

    fileContents, err := ioutil.ReadAll(zipReader)
    if err != nil {
        fmt.Println("[ERROR] ReadAll:", err)
    }

    fmt.Printf("[INFO] Uncompressed contents: %s\n", fileContents)

    // ** Another way of reading the file **
    //
    // fileInfo, _ := handle.Stat()
    // fileContents := make([]byte, fileInfo.Size())
    // bytesRead, err := zipReader.Read(fileContents)
    // if err != nil {
    //     fmt.Println("[ERROR] Reading gzip file:", err)
    // }
    // fmt.Println("[INFO] Number of bytes read from the file:", bytesRead)

    closeFile(handle)
}

func openFile(fileToOpen string) (*os.File, error) {
    return os.OpenFile(fileToOpen, openFileOptions, openFilePermissions)
}

func closeFile(handle *os.File) {
    if handle == nil {
        return
    }

    err := handle.Close()
    if err != nil {
        fmt.Println("[ERROR] Closing file:", err)
    }
}

const openFileOptions int = os.O_CREATE | os.O_RDWR
const openFilePermissions os.FileMode = 0660

有这样一个完整的例子应该有助于将来的参考。

jgzswidk

jgzswidk6#

将接口类型的Go对象压缩为输入

func compress(obj interface{}) ([]byte, error) {
    var b bytes.Buffer
    objBytes, err := json.Marshal(obj)
    if err != nil {
        return nil, err
    }
    gz := gzip.NewWriter(&b)
    defer gz.Close() //NOT SUFFICIENT, DON'T DEFER WRITER OBJECTS
    if _, err := gz.Write(objBytes); err != nil {
        return nil, err
    }
    // NEED TO CLOSE EXPLICITLY
    if err := gz.Close(); err != nil {
        return nil, err
    }
    return b.Bytes(), nil
}

为了解压缩相同的数据,

func decompress(obj []byte) ([]byte, error) {
    r, err := gzip.NewReader(bytes.NewReader(obj))
    if err != nil {
        return nil, err
    }
    defer r.Close()
    res, err := ioutil.ReadAll(r)
    if err != nil {
        return nil, err
    }
    return res, nil
}

注意,如果您在写入后没有关闭Writer对象,ioutil.ReadAll(r)将返回io.EOFio.ErrUnexpectedEOF。我假定在Close()上延迟将正确关闭对象,但它不会。不要延迟写入器对象。

相关问题