doumei1908 2016-01-25 11:31
浏览 4095
已采纳

如何使用lz4压缩和解压缩文件?

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

I am new Go and I cannot figure out how to use this package to compress and 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 Go.

  • 写回答

4条回答 默认 最新

  • douji6735 2016-01-25 13:11
    关注

    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("
    decompressed Data:", string(decompressed[:l]))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?