golang gzip
时间: 2023-10-01 21:10:45 浏览: 61
在 Golang 中,你可以使用 `compress/gzip` 包来进行 gzip 压缩和解压缩操作。下面是一个简单的示例:
```go
package main
import (
"compress/gzip"
"fmt"
"io"
"os"
)
func main() {
// 压缩文件
compressFile("input.txt", "output.txt.gz")
// 解压文件
decompressFile("output.txt.gz", "output.txt")
}
// 压缩文件
func compressFile(inputFile, outputFile string) {
// 打开输入文件
input, err := os.Open(inputFile)
if err != nil {
fmt.Println(err)
return
}
defer input.Close()
// 创建输出文件
output, err := os.Create(outputFile)
if err != nil {
fmt.Println(err)
return
}
defer output.Close()
// 创建 gzip writer
gzipWriter := gzip.NewWriter(output)
defer gzipWriter.Close()
// 复制输入文件内容到 gzip writer
_, err = io.Copy(gzipWriter, input)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("文件压缩完成")
}
// 解压文件
func decompressFile(inputFile, outputFile string) {
// 打开输入文件
input, err := os.Open(inputFile)
if err != nil {
fmt.Println(err)
return
}
defer input.Close()
// 创建输出文件
output, err := os.Create(outputFile)
if err != nil {
fmt.Println(err)
return
}
defer output.Close()
// 创建 gzip reader
gzipReader, err := gzip.NewReader(input)
if err != nil {
fmt.Println(err)
return
}
defer gzipReader.Close()
// 复制 gzip reader 内容到输出文件
_, err = io.Copy(output, gzipReader)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("文件解压缩完成")
}
```
在上面的示例中,`compressFile` 函数用于压缩一个输入文件,并将结果保存到输出文件中。`decompressFile` 函数用于解压一个输入文件,并将结果保存到输出文件中。你可以根据你的需求修改这些函数的参数和行为。请确保已经安装了 Golang 环境,并且将输入文件和输出文件替换为你实际使用的文件路径。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)