美文网首页
go golang 字符串压缩 保存文件

go golang 字符串压缩 保存文件

作者: 不可思议的黄老师 | 来源:发表于2021-09-14 11:41 被阅读0次

需求:
爬取到的字符串或是html大几百kb,几百一千个下来就很大了,所以想下能不能做字符串压缩保存

Golang版本1.17.3

直接上代码

//params string path 完整文件路径 /data/cache/1.txt
//params string s      保存文本内容 
func PutCache(path, s string) {
    dirPath := filepath.Dir(path)
    if _, e := os.Stat(filepath.Dir(path)); e != nil {
        if e := os.MkdirAll(dirPath, 0777); e != nil {
            log.Fatal(e)
        }
    }
    var content bytes.Buffer
    b := []byte(s)
    w := zlib.NewWriter(&content)
    w.Write(b)
    w.Close()
    if e := ioutil.WriteFile(path, content.Bytes(), 0777); e != nil {
        log.Fatal(e)
    }
}

func GetCache(path string) string {
    if _, e := os.Stat(path); e != nil {
        return ""
    } else {
        s, _ := ioutil.ReadFile(path)
        var out bytes.Buffer
        r, e := zlib.NewReader(bytes.NewBuffer(s))
        if e != nil {
            return ""
        }
        if _, e := io.Copy(&out, r); e != nil {
            return ""
        }
        return out.String()
    }
}

自测结果

// 源文件,未处理
html := "example/csdn.html"
b1, _ := ioutil.ReadFile(html)
fmt.Printf("源文件: %s, filesize: %d byte, %dKB \n", html, len(b1), len(b1)/1024)

// 压缩字符串,保存
compress := "cache/csdn.compress.html"
PutCache(compress, string(b1))
b2, _ := ioutil.ReadFile(compress)
fmt.Printf("压缩后文件: %s, filesize: %d byte, %dKB \n", compress, len(b2), len(b2)/1024)

// 取回出来
s := GetCache(compress)
fmt.Printf("提取压缩文件内容 %s, filesize: %d byte, %dKB \n", compress, len(s), len(s)/1024)
D:\Go\Projects\example>go run main.go
源文件: example/csdn.html, filesize: 636786 byte, 621KB
压缩后文件: cache/csdn.compress.html, filesize: 82767 byte, 80KB
提取压缩文件内容 cache/csdn.compress.html, filesize: 636786 byte, 621KB

使用后几百kb只剩下几十kb了

相关文章

网友评论

      本文标题:go golang 字符串压缩 保存文件

      本文链接:https://www.haomeiwen.com/subject/ljpkgltx.html