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
+6.8k Swift : substringWithRange() function example
+5.3k Golang : Return multiple values from function
+19.2k Golang : Delete item from slice based on index/key position
+4.7k MariaDB/MySQL : Form select statement or search query with Chinese characters
+18.4k Golang : Example for RSA package functions
+22k Golang : Join arrays or slices example
+18.5k Golang : Send email with attachment
+4.6k Adding Skype actions such as call and chat into web page examples
+5k Swift : Convert (cast) Float to Int or Int32 value
+14.4k Golang : How to determine if user agent is a mobile device example
+10.1k Golang : Compare files modify date example
+5.7k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example