Golang compress/lzw.NewWriter() function example

package compress/lzw

Golang compress/lzw.NewWriter() function usage example. For compressing data with LZW algorithm.

 package main

 import (
 "compress/lzw"
 "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.lzw")

 if err != nil {
 fmt.Println(err)
 os.Exit(1)
 }

 defer outputFile.Close()

 // The number of bits to use for literal codes, litWidth, must be in the
 // range [2,8] and is typically 8.

 lzwWriter := lzw.NewWriter(outputFile, lzw.LSB, 8) // <---- here !

 if err != nil {
 fmt.Println("NewWriter error ", err)
 os.Exit(1)
 }

 defer lzwWriter.Close()
 io.Copy(lzwWriter, inputFile)

 }

Reference :

https://golang.org/pkg/compress/lzw/#NewWriter

Advertisement