/ 2019-04-17
更多内容可关注公众号:Go程序员开发
缓冲写入
bufio包实现了有缓冲的I/O。它包装一个io.Reader或io.Writer接口对象,创建另一个也实现了该接口,且同时还提供了缓冲和一些文本I/O的帮助函数的对象。
缓冲写入常用函数和方法:
func NewWriter(w io.Writer) *Writer
NewWriter创建一个具有默认大小缓冲、写入w的*Writer。
func NewWriterSize(w io.Writer, size int) *Writer
NewWriterSize创建一个具有最少有size尺寸的缓冲、写入w的Writer。如果参数w已经是一个具有足够大缓冲的Writer类型值,会返回w。
func (b *Writer) Reset(w io.Writer)
Reset丢弃缓冲中的数据,清除任何错误,将b重设为将其输出写入w。
func (b *Writer) Write(p []byte) (nn int, err error)
Write将p的内容写入缓冲。返回写入的字节数。如果返回值nn < len(p),还会返回一个错误说明原因。
func (b *Writer) WriteString(s string) (int, error)
WriteString写入一个字符串。返回写入的字节数。如果返回值nn < len(s),还会返回一个错误说明原因。
func (b *Writer) WriteByte(c byte) error
WriteByte写入单个字节。
func (b *Writer) WriteRune(r rune) (size int, err error)
WriteRune写入一个unicode码值(的utf-8编码),返回写入的字节数和可能的错误。
func (b *Writer) Buffered() int
Buffered返回缓冲中已使用的字节数。
func (b *Writer) Available() int
Available返回缓冲中还有多少字节未使用。
func (b *Writer) Flush() error
Flush方法将缓冲中的数据写入下层的io.Writer接口。
代码实现:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
file, err := os.OpenFile("./file.txt", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Printf("open file err : %v\n", err)
}
if file != nil {
defer func(file *os.File) { file.Close() }(file)
}
fmt.Println("open file success")
write1 := bufio.NewWriter(file)
space1 := write1.Available()
fmt.Printf("默认缓冲区有 %d 字节\n", space1)
insertByte, err := write1.Write([]byte("默认大小缓冲写入\n"))
if err != nil {
fmt.Printf("write err : %v\n", err)
}
fmt.Printf("write success , 写入 %d 字节\n", insertByte)
useSpace1 := write1.Buffered()
fmt.Printf("默认缓冲区已经使用 %d 字节\n", useSpace1)
//丢弃缓冲中的数据
write1.Reset(file)
write2 := bufio.NewWriterSize(file, 10000)
insertByte2, err := write2.WriteString("this is write string test.\n")
if err != nil {
fmt.Printf("write string err : %v\n", err)
}
fmt.Printf("write string success , 写入 %d 字节\n", insertByte2)
err = write2.WriteByte('a')
if err != nil {
fmt.Printf("write byte err : %v\n", err)
}
insertByte3, err := write2.WriteRune('哈')
if err != nil {
fmt.Printf("write rune err : %v\n", err)
}
fmt.Printf("write rune success , 写入 %d 字节\n", insertByte3)
err = write2.Flush()
if err != <span class="" style="margin: 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: inherit !important; font-size: inherit;
(6)