Buffer with bufio
Buffer with bufio
bufio.Reader reads ahead and offers operations such as ReadString. bufio.Writer batches small writes to reduce calls to the underlying writer. Successful buffered writes may not yet have reached the destination. Explicitly Flush and check its error.
package main
import ( "bufio" "fmt" "io" "strings")
func main() { r := bufio.NewReader(strings.NewReader("one\ntwo")) for { line, err := r.ReadString('\n') if len(line) > 0 { fmt.Printf("%q\n", line) } if err == io.EOF { break } if err != nil { fmt.Println(err) break } }}ReadString includes the delimiter when found. The last line has no newline, so it returns two with EOF. Process the text before the error. ReadString can allocate for very long lines; use a bounded approach for untrusted input.
Expected output:
"one\n""two"Flush pending output
package main
import ( "bufio" "bytes" "fmt")
func main() { var dst bytes.Buffer w := bufio.NewWriterSize(&dst, 8) n, err := w.WriteString("abc") fmt.Println(n, err == nil, w.Buffered(), dst.Len()) err = w.Flush() fmt.Println(err == nil, dst.String())}The three bytes fit in the buffer and the destination initially has zero bytes. Flush sends pending data. Successful Flush does not imply durability on disk. File synchronization and closure are separate contracts. Handle Flush errors before claiming success.
Expected output:
3 true 3 0true abcTry it locally
Create a writer of size 16 over a bytes.Buffer. Write "A" and "BC", check errors, print Buffered and destination length, then flush and print the text.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
I/O contracts 06: Buffer with bufio
Check the lesson objective before moving on.
Does successful buffered Write guarantee data has reached the destination?
ReadString returns a nonempty fragment and EOF. What should happen?