Golang : zlib compress file example
This tutorial will show you how to read an uncompress file content into a buffer, use zlib on the buffer and write out the buffer content into a new file.
Here we go :
package main
import (
"bufio"
"bytes"
"compress/zlib"
"flag"
"fmt"
"io/ioutil"
"os"
)
func main() {
flag.Parse() // get the arguments from command line
filename := flag.Arg(0)
if filename == "" {
fmt.Println("Usage : go-zlib sourcefile")
os.Exit(1)
}
rawfile, err := os.Open(filename)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer rawfile.Close()
// calculate the buffer size for rawfile
info, _ := rawfile.Stat()
var size int64 = info.Size()
rawbytes := make([]byte, size)
// read rawfile content into buffer
buffer := bufio.NewReader(rawfile)
_, err = buffer.Read(rawbytes)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
var buf bytes.Buffer
writer := zlib.NewWriter(&buf)
writer.Write(rawbytes)
writer.Close()
err = ioutil.WriteFile(filename+".zlib", buf.Bytes(), info.Mode())
// use 0666 to replace info.Mode() if you prefer
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("%s compressed to %s\n", filename, filename+".zlib")
}
References :
http://golang.org/pkg/compress/zlib/
https://www.socketloop.com/tutorials/golang-read-binary-file-into-memory
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
+5.2k Golang : fmt.Println prints out empty data from struct
+9k Golang : Generate random Chinese, Japanese, Korean and other runes
+7.8k Golang : Append and add item in slice
+7.1k Golang : Process json data with Jason package
+33.5k Golang : convert(cast) bytes to string
+13.1k Golang : Increment string example
+13k Golang : Date and Time formatting
+5.2k How to check with curl if my website or the asset is gzipped ?
+10k Golang : Simple Jawi(Yawi) to Rumi(Latin/Romanize) converter
+11.4k Golang : How to detect a server/machine network interface capabilities?
+28.8k Golang : Saving(serializing) and reading file with GOB