Skip to content
Related Articles

Related Articles

Improve Article

Compressing a File in Golang

  • Difficulty Level : Expert
  • Last Updated : 23 Nov, 2020

As per Wikipedia, data compression or file compression can be understood as a process of reducing the size of a particular file/folder/whatever data while still preserving the original data. Lesser file size has a lot of benefits as it will then occupy lesser storage area giving you more space for other data to occupy, transfer the file faster as the size is lesser and various other perks unlock upon file compression. The compressed files are stored in the form of compressed file extension folders such as “.zip“,”.rar“,”.tar.gz“, “.arj” and “.tgz“. Compression reduces the file size to maximum compression size. If it cannot be compressed further then the size shall remain the same and not lesser.

Below are some following examples to see how compression works in Golang. What are the in-built methods we can use? How a file can be traced using its path? How can we open the file? How does compression work? Let us see the first example

Example 1:

  • To compress a File in Golang, we use the gzip command. 
  • Then create a path to trace our file.
  • Then leave the command to read our file.

Below program reads in a file. It uses ioutil.ReadAll to get all the bytes from the file. After it will create a new file i.e. compressed file by replacing the extension with “gz“. 

Note: To cross-check you can open the compressed file using WinRar or 7-ZIp etc.

Go




package main
  
// Declare all the libraries needed
import (
    "bufio"
    "compress/gzip"
    "fmt"
    "io/ioutil"
    "os"
    "strings"
)
  
func main() {
  
    // Compressing a file takes many steps
      
    // In this example we will see how to open
    // a file
    // Then read all its componenets
    // Create out own file with a gz extension
    // Read all bytes and copy it into our new file
    // Close our new file
    // Let us start now by checking and verifying
    // each step in detail
  
    // Open file on disk.
      
    // Mention the  name of the text file in quoted marks
    // Here we have mentioned the name of the variable
    // which checks the file name as "name_of_file"
    name_of_file := "Gfg.txt"
  
    // After checking this, we would now trace the file path.
    // Now we would use os.Open command
    // This command would help us to open the file
    // This command takes in the path of the file as input.
    f, _ := os.Open("C://ProgramData//" + name_of_file)
  
    // Now let use read the bytes of the document we opened.
    // Create a Reader to get all the bytes from the file.
  
    read := bufio.NewReader(f)
      
    // Now we would use the variable Read All to get all the bytes
    // So we just used variable data which will read all the bytes
    data, _ := ioutil.ReadAll(read)
  
    // Now we would use the extension method
    // Now with the help of replace command we can
    // Replace txt file with gz extension
    // So we would now use the fle name to give 
    // this command a boost
    name_of_file = strings.Replace(name_of_file, ".txt", ".gz", -1)
  
    // Open file for writing
    // Now using the Os.create method we would use the
    // To store thr information of the file gz extension
    f, _ = os.Create("C://ProgramData//" + name_of_file)
  
    // Write compresses Data
    // We would use NewWriter to basically 
    // copy all the compressed data
  
    w := gzip.NewWriter(f)
  
    // With the help of the Writer method, we would
    // write all the bytes in the data variable
    // copied from the original file
    w.Write(data)
  
    // We would now close the file.
    w.Close()
      
    // Now we would see a file with gz extension in the below path
    // This gz entension file we have to open using 7zip tool
   
}

Output:



 

Executing the Program

Output file having gz extension

 

Opening the compressed file using 7-Zip

 

Content of Compressed File – Opening in notepad Directly

Example 2:

Here we have a random string.  Basically, here the user wants to write a compressed version of this string to a file on the disk. So first he has to create a file with os.Create. Now use NewWriter to create a gzip writer targeting that file we created. Now call Write() to write bytes. Convert the string into a byte value using cast expression.
 

Go




package main
  
// Declare all the libraries which are needed.
import (
    "compress/gzip"
    "fmt"
    "os"
)
  
func main() {
  
    // Here we use random text
    // We would now put that random text into a file we created.
    // Once we create a random file we created, we would use
    // that for compression
    // And then we would check its output.
  
    // Now first let us create a random string variable named text
    // This random text will store some characters.
    text := "Geeks for geeks"
  
    // With the help of os.Create command let us
    // first open a file named "file.gz"
  
    // Open a file for writing
    f, _ := os.Create("C:\\ProgramData\\file.gz")
  
    // Create a gzip writer
    // Now we the help of the NewWriter command we simply try
    // to copy all the files into variable "f"
  
    // Let us name this variable p
    p := gzip.NewWriter(f)
  
    // Now with the help of the Write command we will
    // use all the bytes to write it in the file
    // named text.
    p.Write([]byte(text))
  
    // Once we are done copying all the files
    // we would leave the command "close".
  
    // Close the file
    p.Close()
  
    // Now once we are done. To,notify our work
    // We would print the statement "Done"
    fmt.Println("Done")
}

 

Output:

 

Executing the code

File Taken

 

 

Output of compressed file using 7 Zip Tool

Opening the compressed file in Notepad




My Personal Notes arrow_drop_up
Recommended Articles
Page :