如何在 Golang 中壓縮和解壓縮文件

如何在 Golang 中壓縮和解壓縮文件

Gzip 和 Zlib 算法廣泛用於壓縮和解壓縮文件。Gzip 主要用於壓縮單個文件,而 Zlib 主要用於壓縮數據流。這些算法使用 Deflate 壓縮算法進行壓縮,儘管 Gzip 提供了其他功能,包括錯誤檢查和文件元數據。

Gzip 提供了比 Zlib 更好的壓縮比。但是,Gzip 需要更多的處理能力來壓縮和解壓縮數據。在大多數情況下,您應該使用 Gzip 來壓縮文件,使用 Zlib 來壓縮數據流。

Go通過壓縮包提供了壓縮數據的功能,包括文件。

壓縮包

壓縮包內容

壓縮包支持通過 compress/gzip 和 compress/zlib 包壓縮數據,以及其他功能

gzip包支持對gzip 文件格式數據進行壓縮和解壓,包括RFC 1952中規定的讀寫操作。而zlib包有助於壓縮和解壓縮 zlib 格式的數據。

您可以使用import關鍵字從壓縮包中導入gzipzlib 。

import (
    "compress/gzip" // import gzip

    "compress/zlib" // import zlib
)

使用 Gzip 壓縮和解壓縮文件

Gzip 是一種文件格式和用於文件壓縮和解壓縮的軟件應用程序。Gzip 使用 Lempel-Ziv-Markov 鏈算法 (LZ77) 來壓縮數據,該算法通常用於壓縮文本文件,例如 HTML、CSS 或 JavaScript 文件。

使用gzip包壓縮文件的過程簡單直觀。您需要打開文件,創建一個 gzip 文件,創建一個 gzip 寫入器,並在確保寫入過程完成的刷新操作之前將原始文件的內容複製到 gzip 寫入器。

在 Unix 系統上的工作目錄的終端中運行此 bash 命令以創建示例文本文件,然後在該文件中插入文本。

// creates a text file.
touch example.txt

// pipes the string to the file
echo 'Hello, world!' > example.txt}

創建文件並插入文本後,您可以導入gzipioos包進行壓縮操作。

下面介紹如何使用compress/gzip包來壓縮文本文件。

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

func main() {
    // Open the original file
    originalFile, err: = os.Open("example.txt")
    if err! = nil {
        panic(err)
    }
    defer originalFile.Close()

    // Create a new gzipped file
    gzippedFile, err: = os.Create("example.txt.gz")
    if err! = nil {
        panic(err)
    }
    defer gzippedFile.Close()

    // Create a new gzip writer
    gzipWriter: = gzip.NewWriter(gzippedFile)
    defer gzipWriter.Close()

    // Copy the contents of the original file to the gzip writer
    _, err = io.Copy(gzipWriter, originalFile)
    if err! = nil {
        panic(err)
    }

    // Flush the gzip writer to ensure all data is written
    gzipWriter.Flush()
}

os包的Open函數打開文本文件,Close函數用defer語句關閉文件。Create函數創建一個gzip壓縮文件,gzip包的NewWriter函數使用io包的Copy函數將文本文件的內容寫入gzip文件。

一旦壓縮文件上的所有數據都可用, gzipWriter實例的Flush方法就會刷新 gzip writer。

您可以通過解壓縮過程從 gzip 文件中檢索原始文件。解壓縮文件的過程類似;您將打開該文件並創建一個 gzip 文件閱讀器,然後在將內容複製到新文件之前創建一個新文件來保存未壓縮的數據。

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

func main() {
    // Open the gzipped file
    gzippedFile, err: = os.Open("example.txt.gz")
    if err! = nil {
        panic(err)
    }
    defer gzippedFile.Close()

    // Create a new gzip reader
    gzipReader, err: = gzip.NewReader(gzippedFile)
    defer gzipReader.Close()

    // Create a new file to hold the uncompressed data
    uncompressedFile, err: = os.Create("example.txt")
    if err! = nil {
        panic(err)
    }
    defer uncompressedFile.Close()

    // Copy the contents of the gzip reader to the new file
    _, err = io.Copy(uncompressedFile, gzipReader)
    if err! = nil {
        panic(err)
    }
}

os包的Open函數打開gzip壓縮文件, gzip包的NewReader函數讀取壓縮文件。os包的Create函數創建一個新的文本文件。Copy函數將 gzipReader 的內容複製uncompressedFile

使用 Zlib 壓縮和解壓縮數據

Zlib 是一個用於數據壓縮和解壓縮的庫;該庫還使用 LZ77 算法。Zlib 是用 C 編寫的,被廣泛用作其他壓縮庫和軟件的基礎。與gzip不同,zlib是一個庫,zlib不包含文件格式。但是,它通常用於壓縮以容器格式(例如 PNG 或 HTTP)存儲的數據。

使用 zlib 進行壓縮的過程與 gzip 相同。您將創建一個 zlib 文件、配置編寫器、打開原始文件並將內容複製到壓縮文件中。

import (
   "compress/zlib"
   "io"
   "os"
)

func main() {
   // Create a new file "example.zlib"
   file, err: = os.Create("example.zlib")
   // If error occurs, panic and stop the program
   if err! = nil {
       panic(err)
   }
   // Ensure that the file is closed after the function returns
   defer file.Close()

   // Create a new zlib writer with the best compression level
   writer, err: = zlib.NewWriterLevel(file, zlib.BestCompression)
   // If error occurs, panic and stop the program
   if err! = nil {
       panic(err)
   }
   // Ensure that the writer is closed after the function returns
   defer writer.Close()

   // Open the input file "example.txt"
   inputFile, err: = os.Open("example.txt")
   // If error occurs, panic and stop the program
   if err! = nil {
       panic(err)
   }
   // Ensure that the input file is closed after the function returns
   defer inputFile.Close()

   // Copy the contents of the input file to the writer
   io.Copy(writer, inputFile)
}

Create方法創建 zlib 文件,NewWriterLevel函數使用指定選項(在本例中為BestCompression選項)為文件創建編寫器。os包的Open方法打開文本文件,io包的Copy函數在壓縮過程中將文本文件的內容複製到zlib文件中。

要解壓縮 zlib 文件,您需要打開壓縮文件,創建一個新的 zlib 閱讀器,然後最後將閱讀器的內容複製到標準輸出。

import (
   "compress/zlib"
   "io"
   "os"
)

func main() {
   // Open the compressed file "compressed_file.zlib"
   file, err: = os.Open("compressed_file.zlib")
   // If error occurs, panic and stop the program
   if err! = nil {
       panic(err)
   }
   // Ensure that the file is closed after the function returns
   defer file.Close()

   // Create a new zlib reader for the compressed file
   reader, err: = zlib.NewReader(file)
   // If error occurs, panic and stop the program
   if err! = nil {
       panic(err)
   }
   // Ensure that the reader is closed after the function returns
   defer reader.Close()

   // Copy the contents of the reader to the standard output
   io.Copy(os.Stdout, reader)
}

main函數用os包的Open函數打開zlib文件, zlib包的NewReader函數將zlib文件讀入reader實例。io包的Copy方法將內容從閱讀器複製到標準輸出(在本例中為控制台)。

壓縮文件中文本的輸出

使用這些工具進行文件壓縮

為文件壓縮編寫代碼對於自動化任務和壓縮多個文件很方便。如果您只需要壓縮幾個文件,您可以使用 WinRar、WinZip、Express Zip 和 Bandizip 等應用程序。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *