io.Reader / Writer / bufio
Go's I/O is abstracted through interfaces, centered around io.Reader and io.Writer. The bufio package provides efficient I/O through buffering.
Syntax
// io.Reader interface (for reading)
type Reader interface {
Read(p []byte) (n int, err error)
}
// io.Writer interface (for writing)
type Writer interface {
Write(p []byte) (n int, err error)
}
// Create a buffered reader
br := bufio.NewReader(reader)
// Create a buffered writer
bw := bufio.NewWriter(writer)
// Create a scanner that reads line by line
scanner := bufio.NewScanner(reader)
Function List
| Function / Method | Description |
|---|---|
| bufio.NewReader(r) | Creates a buffered reader wrapping an io.Reader. Reads large data efficiently. |
| bufio.NewWriter(w) | Creates a buffered writer wrapping an io.Writer. Batches small writes together for better performance. |
| bufio.NewScanner(r) | Creates a scanner that reads text line by line or word by word. |
| scanner.Scan() | Reads the next token (a line by default). Returns false when there is no more data. |
| scanner.Text() | Returns the token read by the most recent Scan() call as a string. |
| bw.Flush() | Writes any buffered data to the underlying output. Always call this after writing. |
| io.Copy(dst, src) | Copies data from src to dst. Useful for tasks like copying files. |
Sample Code
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
// Create a Reader from a string and read it line by line
text := "Line 1\nLine 2\nLine 3\n"
reader := strings.NewReader(text)
scanner := bufio.NewScanner(reader)
fmt.Println("--- Reading line by line ---")
for scanner.Scan() {
fmt.Println(scanner.Text())
}
// Write using bufio.Writer
bw := bufio.NewWriter(os.Stdout)
fmt.Fprintln(bw, "--- Buffered writing ---")
fmt.Fprintln(bw, "Writing to buffer...")
bw.Flush() // Output won't appear without Flush
// Read a file line by line using bufio.Reader
f, _ := os.CreateTemp("", "sample*.txt")
defer os.Remove(f.Name())
f.WriteString("hello\nworld\n")
f.Seek(0, 0)
br := bufio.NewReader(f)
for {
line, err := br.ReadString('\n')
fmt.Print("Read: ", line)
if err != nil {
break
}
}
}
Overview
io.Reader and io.Writer are at the core of Go's I/O design. Because files, network connections, strings, and other data sources all share the same interfaces, you can write highly reusable code.
bufio speeds up I/O by reducing the number of system calls. When using bufio.Writer, always call Flush() at the end. If you forget, the buffered content will not be written to the output. For reading text files line by line, bufio.Scanner is the most concise option.
If you find any errors or copyright issues, please contact us.