Compressing a File in Golang
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
- 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.
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.