在go语言中用compress/flate例子压缩和解压文件示例
一个关于如何使用go语言中的compress/flate包来压缩文件。Package flate实现了DEFLATE压缩数据格式,如RFC 1951所述。
要压缩一个文件,用NewWriter()函数将数据管道化并冲出:
示例代码:
package main
import (
"compress/flate"
"fmt"
"io"
"os"
)
func main() {
inputFile, err := os.Open("file.txt")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer inputFile.Close()
outputFile, err := os.Create("file.txt.compressed")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer outputFile.Close()
flateWriter, err := flate.NewWriter(outputFile, flate.BestCompression)
if err != nil {
fmt.Println("NewWriter error ", err)
os.Exit(1)
}
defer flateWriter.Close()
io.Copy(flateWriter, inputFile)
flateWriter.Flush()
}
测试数据样本:
>cat file.txt
This is a test file for Golang Compress/Flate
This is a test file for Golang Compress/Flate
This is a test file for Golang Compress/Flate
This is a test file for Golang Compress/Flate
This is a test file for Golang Compress/Flate
This is a test file for Golang Compress/Flate
>cat file.txt.compressed
??,V?D??????T?"???t?????b}??T?Q?#U5????
要解压文件,在将解压后的数据输送到文件之前,用NewReader()函数读入压缩数据
package main
import (
"compress/flate"
"fmt"
"io"
"os"
)
func main() {
inputFile, err := os.Open("file.txt.compressed")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer inputFile.Close()
outputFile, err := os.Create("file.txt.decompressed")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer outputFile.Close()
flateReader := flate.NewReader(inputFile)
defer flateReader.Close()
io.Copy(outputFile, flateReader)
}
相关文章:
在go语言中Gzip文件压缩实例
https://www.zongscan.com/demo333/96109.html
相关文章