如何在Golang中使用lz4压缩和解压文件? [英] How to compress and decompress a file using lz4 in Golang?

查看:1826
本文介绍了如何在Golang中使用lz4压缩和解压文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在golang中使用lz4算法压缩和解压文件。有没有可用的软件包来做到这一点?
我搜索并找到一个名为
的软件包 https://github.com/pierrec/lz4



我是新的Golang,我无法弄清楚如何使用这个软件包来压缩&解压文件。



我需要使用这个包来将压缩一个文件放到二进制文件中格式并使用Golang解压缩二进制文件原始文件



谢谢 解决方案

这是使用 github.com/pierrec/lz4 软件包压缩和解压缩的最简单的例子。

  //压缩项目main.go 
软件包主要

导入fmt
导入github.com/pierrec/lz4

var fileContent =`CompressBlock将从soffet开始的源缓冲区压缩到目标缓冲区。
这是LZ4压缩的快速版本,也是默认版本。
返回压缩数据的大小。如果它是0并且没有错误,那么数据是不可压缩的。
如果目标缓冲区太小,则返回错误。

func main(){
toCompress:= [] byte(fileContent)
compressed:= make([] byte,len(toCompress))

//压缩
l,err:= lz4.CompressBlock(toCompress,compressed,0)
if err!= nil {
panic(err)
}
fmt.Println(compressed Data:,string(compressed [:l]))

//解压缩
解压缩:= make([] byte,len(toCompress))
l,err = lz4.UncompressBlock(compressed [:l],decompressed,0)
if err!= nil {
panic(err)
}
fmt.Println(\ ndecompressed Data:,string(decompressed [:l]))
}


I want to compress and decompress a file using lz4 algorithm in golang. Is there any package available to do this? I searched and found a package called https://github.com/pierrec/lz4

I am new Golang and i cannot figure out how to use this package to compress & decompress a file.

I need to use this package to compress a file to binary format and decompress the binary file to original file using Golang.

Thanks

解决方案

I think blow example should direct you to correct direction. It is the simplest example of how to compress and decompress using github.com/pierrec/lz4 package.

//compress project main.go
package main

import "fmt"
import "github.com/pierrec/lz4"

var fileContent = `CompressBlock compresses the source buffer starting at soffet into the destination one.
This is the fast version of LZ4 compression and also the default one.
The size of the compressed data is returned. If it is 0 and no error, then the data is incompressible.
An error is returned if the destination buffer is too small.`

func main() {
    toCompress := []byte(fileContent)
    compressed := make([]byte, len(toCompress))

    //compress
    l, err := lz4.CompressBlock(toCompress, compressed, 0)
    if err != nil {
        panic(err)
    }
    fmt.Println("compressed Data:", string(compressed[:l]))

    //decompress
    decompressed := make([]byte, len(toCompress))
    l, err = lz4.UncompressBlock(compressed[:l], decompressed, 0)
    if err != nil {
        panic(err)
    }
    fmt.Println("\ndecompressed Data:", string(decompressed[:l]))
}

这篇关于如何在Golang中使用lz4压缩和解压文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆