怎么在Golang中使用zlib对字符串进行压缩和解压缩?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
zlib.NewWriter() 只能传递 []byte类型数据. NewWriterLevel 可以传递压缩的等级.
package main import ( "bytes" "compress/zlib" "fmt" "io" ) func main() { var in bytes.Buffer b := []byte(`xiorui.cc`) w := zlib.NewWriter(&in) w.Write(b) w.Close() var out bytes.Buffer r, _ := zlib.NewReader(&in) io.Copy(&out, r) fmt.Println(out.String()) }
库包地址
import "compress/zlib"
写入
func NewWriter func NewWriter(w io.Writer) *Writer
读取压缩的数据
func NewReader func NewReader(r io.Reader) (io.ReadCloser, error)
设置压缩等级,并压缩数据
func NewWriterLevel(w io.Writer, level int) (io.WriteCloser, os.Error)
下面是几个级别.
const ( NoCompression = 0 BestSpeed = 1 BestCompression = 9 DefaultCompression = -1 ) const ( NoCompression = flate.NoCompression BestSpeed = flate.BestSpeed BestCompression = flate.BestCompression DefaultCompression = flate.DefaultCompression )
写入数据
func (*Writer) Write func (z *Writer) Write(p []byte) (n int, err error)
关闭
func (*Writer) Close func (z *Writer) Close() error