Golang 中的 Bufio 包詳解之 Bufio.Reader
bufio.Reader
bufio.Reader 是一個帶有緩沖區(qū)的 io.Reader 接口的實現(xiàn),提供了一系列方法來幫助讀取數(shù)據(jù)。使用 bufio.Reader 可以減少 I/O 操作,降低讀取數(shù)據(jù)的時間和資源開銷。主要特征是它會在內存中存儲從底層 io.Reader 中讀取到的數(shù)據(jù),然后先從內存緩沖區(qū)中讀取數(shù)據(jù),這樣可以減少訪問底層 io.Reader 對象的次數(shù)以及減輕操作系統(tǒng)的壓力。結構體定義和對應的方法如下:
type Reader struct {
buf []byte
rd io.Reader // reader provided by the client
r, w int // buf read and write positions
err error
lastByte int // last byte read for UnreadByte; -1 means invalid
lastRuneSize int // size of last rune read for UnreadRune; -1 means invalid
}
下面是 bufio.Reader 的一些主要方法:
- func (b *Reader) Read(p []byte) (n int, err error):從緩沖區(qū)中讀取數(shù)據(jù)到 p 中,返回讀取的字節(jié)數(shù)和可能的讀取錯誤。如果 p 的長度大于緩沖區(qū)的大小,則會觸發(fā)緩沖區(qū)的擴容操作。
- func (b *Reader) ReadByte() (byte, error):從緩沖區(qū)中讀取一個字節(jié),并返回該字節(jié)和可能發(fā)生的錯誤信息。
- func (b *Reader) ReadRune() (r rune, size int, err error):從緩沖區(qū)中讀取一個 UTF-8 編碼的字符,返回該字符和可能發(fā)生的錯誤。如果緩沖區(qū)中沒有足夠的字節(jié)來表示一個完整的 UTF-8 字符,則返回一個錯誤。
- func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error):從緩沖區(qū)中讀取一行,并返回該行內容和可能發(fā)生的錯誤。
其他方法就不一一說明了,最好自己去看去使用去體會。
優(yōu)勢
bufio.Reader 提供了帶緩沖的讀取操作,先在內存中存儲通過系統(tǒng)調用讀取到的數(shù)據(jù),然后從內存緩沖區(qū)中讀取數(shù)據(jù),大大減少了系統(tǒng)調用次數(shù),減輕了操作系統(tǒng)的壓力,加快了數(shù)據(jù)讀取速度。
bufio.Reader 提供了很多類型的讀取方法,例如 ReadByte()、 ReadRune() 和 ReadLine() 等,使用起來非常方便。
使用示例
簡單使用示例如下:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
panic(err)
}
defer file.Close()
reader := bufio.NewReader(file)
buffer := make([]byte, 4)
for {
n, err := reader.Read(buffer)
if err != nil {
break
}
fmt.Print(string(buffer[:n]))
}
}
使用 NewReader() 方法創(chuàng)建一個 bufio.Reader 實例,然后創(chuàng)建了一個緩沖區(qū) buffer,并在一個循環(huán)中使用 Read() 方法從緩沖區(qū)中讀取數(shù)據(jù)。
小結
bufio.Reader 提供了帶緩沖的讀取操作和豐富的讀取操作方法,特別是讀取大塊數(shù)據(jù)時,使用 bufio.Reader 可以顯著提高程序的性能和響應速度。