Compressing a File in Golang
Last Updated :
28 Jul, 2022
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 components
// 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 file 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 the 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 extension 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 DirectlyExample 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
Similar Reads
Composition in Golang Composition is a method employed to write re-usable segments of code. It is achieved when objects are made up of other smaller objects with particular behaviors, in other words, Larger objects with a wider functionality are embedded with smaller objects with specific behaviors. The end goal of compo
5 min read
How to Read a CSV File in Golang? Golang offers a vast inbuilt library that can be used to perform read and write operations on files. To read a CSV file, the following methods are used in Golang: os.Open(): The os.Open() method opens the named file for reading. This method returns either the os.File pointer or an error. encoding/cs
4 min read
How to Create an Empty File in Golang? Like other programming languages, Go language also allows you to create files. For creating a file it provides Create() function, this function is used to create or truncates the given named file. This method will truncate the file, if the given file is already exists. This method will create a file
2 min read
Encapsulation in Golang Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. In a different way, encapsulation is a protective shield that prevents the data from being accessed by the code outside this shield. In object-oriented l
4 min read
filepath.Abs() Function in Golang With Examples In Go language, path package used for paths separated by forwarding slashes, such as the paths in URLs. The filepath.Abs() function in Go language used to return an absolute representation of the specified path. If the path is not absolute it will be joined with the current working directory to turn
2 min read
Channel in Golang In Go language, a channel is a medium through which a goroutine communicates with another goroutine and this communication is lock-free. Or in other words, a channel is a technique which allows to let one goroutine to send data to another goroutine. By default channel is bidirectional, means the gor
7 min read
Perl | Appending to a File When a file is opened in write mode using â>â, the content of the existing file is deleted and content added using the print statement is written to the file. In this mode, the writing point will be set to the end of the file. So old content of file remains intact and anything that is written to
2 min read
filepath.Base() Function in Golang With Examples In Go language, path package used for paths separated by forwarding slashes, such as the paths in URLs. The filepath.Base() function in Go language used to return the last element of the specified path. Here the trailing path separators are removed before extracting the last element. If the path is
2 min read
fmt.Fscan() Function in Golang With Examples In Go language, fmt package implements formatted I/O with functions analogous to C's printf() and scanf() function. The fmt.Fscan() function in Go language scans the specified text, read from r, and then stores the successive space-separated values into successive arguments. Here newlines get counte
3 min read
Time Formatting in Golang Golang supports time formatting and parsing via pattern-based layouts. To format time, we use the Format() method which formats a time.Time object. Syntax: func (t Time) Format(layout string) string We can either provide custom format or predefined date and timestamp format constants are also availa
2 min read