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
+3.3k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+10.8k Golang : Determine if time variables have same calendar day
+16.7k Golang : Get all upper case or lower case characters from string example
+11.8k Golang : Convert IPv4 address to packed 32-bit binary format
+7.4k Golang : Implementing class(object-oriented programming style)
+9.9k Golang : Web routing/multiplex example
+18.6k Golang : Append content to a file
+8.2k Golang : Create unique title slugs example
+21.7k Golang : Get ASCII code from a key press(cross-platform) example
+5k Fix ERROR 2003 (HY000): Can't connect to MySQL server on 'IP address' (111)
+13.2k Golang : How to get URL port?
+7.2k Golang : Emulate NumPy way of creating matrix example