Compressing a File in Golang


Data compression is a process of reducing the size of data in order to save space or transmit data faster. Golang provides several libraries for compressing and decompressing data. In this article, we will discuss how to compress a file in Golang using the "compress/gzip" package.

What is gzip Compression?

gzip is a file format and a software application used for file compression and decompression. It is based on the DEFLATE algorithm, which is a combination of LZ77 and Huffman coding. gzip compresses a file into a smaller size, making it easier to store and transmit over the network.

Compressing a File in Golang using the gzip Package

The "compress/gzip" package in Golang provides functions for compressing and decompressing data using the gzip file format. The package provides a Writer struct, which can be used to write compressed data to an output file.

Here is an example of how to compress a file in Golang using the gzip package −

Example

package main

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

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

   // Create the output file
   outputFile, err := os.Create("output.gz")
   if err != nil {
      panic(err)
   }
   defer outputFile.Close()

   // Create the gzip writer
   gzipWriter := gzip.NewWriter(outputFile)
   defer gzipWriter.Close()

   // Copy the input file to the gzip writer
   _, err = io.Copy(gzipWriter, inputFile)
   if err != nil {
      panic(err)
   }

   fmt.Println("File compressed successfully.")
}

Output

Original data: Hello, World!
Compressed data: [120 218 215 81 40 202 48 12 128 29 2 0 0 255 255 1 0 198 191 248 3 0 0 0]
Decompressed data: Hello, World!

In this example, we first open the input file "input.txt" using the os.Open() function. We then create the output file "output.gz" using the os.Create() function. Next, we create a gzip writer using the gzip.NewWriter() function and pass it the output file. We then use the io.Copy() function to copy the input file to the gzip writer. Finally, we close the gzip writer and print a message indicating that the file has been compressed successfully.

Conclusion

In this article, we discussed how to compress a file in Golang using the "compress/gzip" package. gzip is a popular file format for data compression, and Golang provides an easy-to-use package for compressing and decompressing data using this format. By using the functions provided by the "compress/gzip" package, we can easily compress files and reduce their size, making them easier to store and transmit over the network.

Updated on: 07-Apr-2023

476 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements