bufio package implements buffered I/O. It wraps an io.Reader or io.Writer object, creating another object (Reader or Writer) that also implements the interface but provides buffering and some help for textual I/O.
Key Types
Reader
Implements buffering for anio.Reader object.
Writer
Implements buffering for anio.Writer object.
Scanner
Provides a convenient interface for reading data such as a file of newline-delimited lines of text.Common Operations
Reading Lines
Reading with Peek
Reading Until Delimiter
Buffered Writing
Custom Split Function
Key Methods
Reader Methods
Read(p []byte)- Read data into pReadByte()- Read a single byteReadRune()- Read a single UTF-8 encoded Unicode characterReadLine()- Read a line of bytesReadString(delim byte)- Read until delimiterReadBytes(delim byte)- Read until delimiter, return bytesPeek(n int)- Return next n bytes without advancing reader
Writer Methods
Write(p []byte)- Write data from pWriteByte(c byte)- Write a single byteWriteRune(r rune)- Write a single Unicode code pointWriteString(s string)- Write a stringFlush()- Write buffered data to underlying writer
Scanner Methods
Scan()- Advance to next tokenText()- Return most recent token as stringBytes()- Return most recent token as byte sliceErr()- Return first error encounteredSplit(split SplitFunc)- Set split function
Default Buffer Sizes
- Default Reader buffer: 4096 bytes
- Default Writer buffer: 4096 bytes
- Scanner max token size: 64KB (configurable with
Buffermethod)
Error Handling
Performance Tips
- Choose appropriate buffer size - Larger buffers reduce system calls but use more memory
- Always flush writers - Use
defer w.Flush()to ensure data is written - Reuse buffers - Use
Reset()to reuse Reader/Writer with new underlying streams - Scanner for line-based input - More convenient than manual ReadLine calls
Common Use Cases
- Reading configuration files line by line
- Processing log files
- Parsing CSV or structured text data
- Network protocol implementation
- Improving performance of small, frequent I/O operations