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
import (
"bufio"
"compress/gzip"
"fmt"
"io/ioutil"
"os"
"strings"
)
func main() {
name_of_file := "Gfg.txt"
read := bufio.NewReader(f)
data, _ := ioutil.ReadAll(read)
name_of_file = strings.Replace(name_of_file, ".txt" , ".gz" , - 1 )
w := gzip.NewWriter(f)
w.Write(data)
w.Close()
}
|
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
import (
"compress/gzip"
"fmt"
"os"
)
func main() {
text := "Geeks for geeks"
f, _ := os.Create( "C:\\ProgramData\\file.gz" )
p := gzip.NewWriter(f)
p.Write([] byte (text))
p.Close()
fmt.Println( "Done" )
}
|
Output:

Executing the code

File Taken

Output of compressed file using 7 Zip Tool

Opening the compressed file in Notepad