Files
bulma/bufio_write_demo.go
T

31 lines
702 B
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
// 打开文件(创建+追加模式)
file, err := os.OpenFile("batch_write.log",
os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
fmt.Printf("文件打开失败:%v\n", err)
return
}
defer file.Close()
// 初始化4KB缓冲区(默认4096字节,可按场景调整)
writer := bufio.NewWriterSize(file, 4096)
defer writer.Flush() // 退出前确保缓冲区数据写入文件
// 批量写入1000条记录
for i := 0; i < 1000; i++ {
fmt.Fprintf(writer, "批量记录%d%s\n",
i, "这是一条批量写入的数据")
}
fmt.Println("批量写入完成,缓冲区数据将由defer自动Flush")
}