如何在 Go 中写入 gzip 文件
此示例展示如何使用 Go 的 gzip 库直接写入 gzip 压缩数据。
首先,打开文件并使用 gzip.NewWriter() 在其上创建新的 io.Writer:
create_gzip_writer.go
// 打开文件
f, _ := os.Create("test.txt.gz")
defer f.Close()
// 创建 gzip 写入器
gzWriter := gzip.NewWriter(f)现在你可以 gzWriter.Write()。不要忘记 gzWriter.Close()
write_gzip_content.go
content := "Hello World!"
gzWriter.Write([]byte(content))
gzWriter.Close()完整示例:
gzip_full_example.go
package main
import (
"compress/gzip"
"os"
)
func main() {
// 打开文件
f, _ := os.Create("test.txt.gz")
defer f.Close()
// 创建 gzip 写入器
gzWriter := gzip.NewWriter(f)
// 写入内容并关闭
content := "Hello World!"
gzWriter.Write([]byte(content))
gzWriter.Close()
}你可以使用 zcat test.txt.gz 来查看内容已正确写入文件。
Check out similar posts by category:
Go
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow