写完一定要flush!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
gz := gzip.NewWriter(&res)
gz.Write(s)
gz.Flush()
package main
import (
"bytes"
"compress/gzip"
"encoding/binary"
"fmt"
"io/ioutil"
)
var (
path = "D:\\code\\go\\goland\\file-go\\t.jpg"
outZip = "D:\\code\\go\\goland\\file-go\\t.zip"
outUnzip = "D:\\code\\go\\goland\\file-go\\t2.unzip.jpg"
)
func testZip() {
s, r := ioutil.ReadFile(path)
fmt.Println(s, r)
fmt.Println(len(s))
fmt.Printf("%T\n", s)
var res bytes.Buffer
gz := gzip.NewWriter(&res)
gz.Write(s)
gz.Flush()
fmt.Println("res", res)
fmt.Println("res")
fmt.Println("by", len(res.Bytes()))
ioutil.WriteFile(outZip, res.Bytes(), 0777)
}
func testUnzip() {
s, _ := ioutil.ReadFile(outZip)
fmt.Println(len(s))
var res bytes.Buffer
binary.Write(&res, binary.LittleEndian, s)
fmt.Println(len(res.Bytes()))
gz, _ := gzip.NewReader(&res)
data, _ := ioutil.ReadAll(gz)
defer gz.Close()
fmt.Println(len(data))
ioutil.WriteFile(outUnzip, data, 0777)
}
func main() {
fmt.Println("zip")
testZip()
fmt.Println("unzip")
testUnzip()
}
来源:oschina
链接:https://my.oschina.net/ahaoboy/blog/3211408