Golang : Decompress zlib file example
Continuation from previous tutorial on how to zlib compress a file. In this part, we will learn how to decompress a file that was compressed with zlib compression algorithm.
Here are the codes :
package main
import (
"compress/zlib"
"flag"
"fmt"
"io"
"os"
"strings"
)
func main() {
flag.Parse() // get the arguments from command line
filename := flag.Arg(0)
if filename == "" {
fmt.Println("Usage : unzlib sourcefile.zlib")
os.Exit(1)
}
zlibfile, err := os.Open(filename)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
reader, err := zlib.NewReader(zlibfile)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer reader.Close()
newfilename := strings.TrimSuffix(filename, ".zlib")
writer, err := os.Create(newfilename)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer writer.Close()
if _, err = io.Copy(writer, reader); err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Decompressed to ", newfilename)
}
Sample output :
./unzlib uncompressed.txt.zlib
Decompressed to uncompressed.txt
./unzlib
Usage : unzlib sourcefile.zlib
References :
http://golang.org/pkg/compress/zlib/
https://www.socketloop.com/tutorials/golang-zlib-compress-file-example
See also : Golang : zlib compress 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
+10.3k Golang : Detect number of faces or vehicles in a photo
+21.1k Golang : Convert(cast) string to rune and back to string example
+6.1k PHP : Get client IP address
+7.8k Golang : Load DSA public key from file example
+11.1k Golang : How to determine a prime number?
+3.7k Java : Random alphabets, alpha-numeric or numbers only string generator
+5.3k Golang : Generate Interleaved 2 inch by 5 inch barcode
+14k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+6k Golang : Experimenting with the Rejang script
+14k Golang : Compress and decompress file with compress/flate example
+15.2k Golang : How to check if IP address is in range
+5k Golang : Calculate a pip value and distance to target profit example