Golang : Compress and decompress file with compress/flate example
A quick and simple tutorial on how to compress a file with Golang's compress/flate
package. Package flate implements the DEFLATE compressed data format, as described in RFC 1951.
To compress a file, pipe and flush the data out with NewWriter()
function :
package main
import (
"compress/flate"
"fmt"
"io"
"os"
)
func main() {
inputFile, err := os.Open("file.txt")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer inputFile.Close()
outputFile, err := os.Create("file.txt.compressed")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer outputFile.Close()
flateWriter, err := flate.NewWriter(outputFile, flate.BestCompression)
if err != nil {
fmt.Println("NewWriter error ", err)
os.Exit(1)
}
defer flateWriter.Close()
io.Copy(flateWriter, inputFile)
flateWriter.Flush()
}
Sample test data :
>cat file.txt
This is a test file for Golang Compress/Flate
This is a test file for Golang Compress/Flate
This is a test file for Golang Compress/Flate
This is a test file for Golang Compress/Flate
This is a test file for Golang Compress/Flate
This is a test file for Golang Compress/Flate
>cat file.txt.compressed
��,V�D������T���"��ļt��܂���b}��ĒT�Q�#U5����
To decompress the file, read in the compressed data with NewReader()
function before piping out the decompressed data to file
package main
import (
"compress/flate"
"fmt"
"io"
"os"
)
func main() {
inputFile, err := os.Open("file.txt.compressed")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer inputFile.Close()
outputFile, err := os.Create("file.txt.decompressed")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer outputFile.Close()
flateReader := flate.NewReader(inputFile)
defer flateReader.Close()
io.Copy(outputFile, flateReader)
}
Happy coding!
Reference :
See also : Golang : Gzip file example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+19.8k Golang : How to get time zone and load different time zone?
+6.3k Golang : Dealing with struct's private part
+26.5k Get file path of temporary file in Go
+6.3k Golang : How to stop user from directly running an executable file?
+26.8k Golang : Read, Write(Create) and Delete Cookie example
+3.5k Javascript : Detect when console is activated and do something about it
+10.3k Golang : Display a text file line by line with line number example
+29.7k Golang : Get local IP and MAC address
+19.3k Golang : Convert PNG transparent background image to JPG or JPEG image
+10.1k Golang : Find age or leap age from date of birth example
+5.8k Mac OSX : Find large files by size
+7.5k Golang : Another camera capture GUI application with GTK and OpenCV