這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
Go bufio包
Package bufio 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.
bufio.Reader結構體
// Reader implements buffering for an io.Reader object.type Reader struct {buf []byterd io.Reader // reader provided by the clientr, w int // buf read and write positionserr errorlastByte intlastRuneSize int}
所有的方法,
func NewReader(rd io.Reader) *Readerfunc NewReaderSize(rd io.Reader, size int) *Readerfunc (b *Reader) Buffered() intfunc (b *Reader) Discard(n int) (discarded int, err error)func (b *Reader) Peek(n int) ([]byte, error)func (b *Reader) Read(p []byte) (n int, err error)func (b *Reader) ReadByte() (byte, error)func (b *Reader) ReadBytes(delim byte) ([]byte, error)func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error)func (b *Reader) ReadRune() (r rune, size int, err error)func (b *Reader) ReadSlice(delim byte) (line []byte, err error)func (b *Reader) ReadString(delim byte) (string, error)func (b *Reader) Reset(r io.Reader)func (b *Reader) UnreadByte() errorfunc (b *Reader) UnreadRune() errorfunc (b *Reader) WriteTo(w io.Writer) (n int64, err error)
使用樣本,
package mainimport ("bytes""bufio""fmt")func main() {b1 := []byte("hello world!")rd := bytes.NewReader(b1)buf := bufio.NewReader(rd) //預設的緩衝區大小是 4096fmt.Printf("1.the number of bytes that can be read from the current buffer=%d\n", buf.Buffered())b2 := make([]byte, 5)buf.Read(b2)println(string(b2))fmt.Printf("2.the number of bytes that can be read from the current buffer=%d\n", buf.Buffered())d, _ := buf.Discard(1)fmt.Printf("3.the number of discard bytes =%d\n", d)b3 := make([]byte, 5)buf.Read(b3)println(string(b3))fmt.Printf("4.the number of bytes that can be read from the current buffer=%d\n", buf.Buffered())fmt.Println("--------------")rd2 := bytes.NewReader([]byte("hello world"))buf2 := bufio.NewReader(rd2)// Peek 返回緩衝的一個切片,該切片引用緩衝中前 n 個位元組的資料,// 該操作不會將資料讀出,只是引用,引用的資料在下一次讀取操作之// 前是有效。如果切片長度小於 n,則返回一個錯誤資訊說明原因。// 如果 n 大於緩衝的總大小,則返回 ErrBufferFull。b4, _ := buf2.Peek(5)println(string(b4))b4[0] = 'a'b4[1] = 'a'b4[2] = 'a'b4[3] = 'a'b4[4] = 'a'fmt.Printf("5.the number of bytes that can be read from the current buffer=%d\n", buf2.Buffered())for {b, err := buf2.ReadByte()if err != nil {break}fmt.Print(string(b)) // aaaaa world}}
bufio.Writer結構體
// Writer implements buffering for an io.Writer object.// If an error occurs writing to a Writer, no more data will be// accepted and all subsequent writes will return the error.// After all data has been written, the client should call the// Flush method to guarantee all data has been forwarded to// the underlying io.Writer.type Writer struct {err errorbuf []byten intwr io.Writer}
所有的方法,
func NewWriter(w io.Writer) *Writerfunc NewWriterSize(w io.Writer, size int) *Writerfunc (b *Writer) Available() intfunc (b *Writer) Buffered() intfunc (b *Writer) Flush() errorfunc (b *Writer) ReadFrom(r io.Reader) (n int64, err error)func (b *Writer) Reset(w io.Writer)func (b *Writer) Write(p []byte) (nn int, err error)func (b *Writer) WriteByte(c byte) errorfunc (b *Writer) WriteRune(r rune) (size int, err error)func (b *Writer) WriteString(s string) (int, error)
方法使用樣本,
package mainimport ("bufio""os""fmt")func main() {buf := bufio.NewWriterSize(os.Stdout, 0)fmt.Println(buf.Available(), buf.Buffered())buf.WriteString("hello world")fmt.Println(buf.Available(), buf.Buffered())str := "我是中國人"for _, ele := range []rune(str) {buf.WriteRune(ele)}// 緩衝後統一輸出,避免終端頻繁重新整理,影響速度buf.Flush()}
bufio.Scanner結構體
// Scanner provides a convenient interface for reading data such as// a file of newline-delimited lines of text. Successive calls to// the Scan method will step through the 'tokens' of a file, skipping// the bytes between the tokens. The specification of a token is// defined by a split function of type SplitFunc; the default split// function breaks the input into lines with line termination stripped. Split// functions are defined in this package for scanning a file into// lines, bytes, UTF-8-encoded runes, and space-delimited words. The// client may instead provide a custom split function.//// Scanning stops unrecoverably at EOF, the first I/O error, or a token too// large to fit in the buffer. When a scan stops, the reader may have// advanced arbitrarily far past the last token. Programs that need more// control over error handling or large tokens, or must run sequential scans// on a reader, should use bufio.Reader instead.//type Scanner struct {r io.Reader // The reader provided by the client.split SplitFunc // The function to split the tokens.maxTokenSize int // Maximum size of a token; modified by tests.token []byte // Last token returned by split.buf []byte // Buffer used as argument to split.start int // First non-processed byte in buf.end int // End of data in buf.err error // Sticky error.empties int // Count of successive empty tokens.scanCalled bool // Scan has been called; buffer is in use.done bool // Scan has finished.}
所有的方法,
func NewScanner(r io.Reader) *Scannerfunc (s *Scanner) Buffer(buf []byte, max int)func (s *Scanner) Bytes() []bytefunc (s *Scanner) Err() errorfunc (s *Scanner) Scan() boolfunc (s *Scanner) Split(split SplitFunc)func (s *Scanner) Text() string
方法使用樣本,
package mainimport ("os""bufio""fmt")func main() {var path = "/Users/xinxingegeya/workspace-go/src/awesomeProject/bufio/temp.txt"file, _ := os.Open(path)scanner := bufio.NewScanner(file)// Split 用於設定“匹配函數”,這個函數必須在調用 Scan 前執行。scanner.Split(bufio.ScanLines)// Scan 開始一次掃描過程,如果匹配成功,可以通過 Bytes() 或 Text() 方法取出結果,// 如果遇到錯誤,則終止掃描,並返回 false。for scanner.Scan() {var record = scanner.Text()fmt.Println(record)}}
bufio.ReaderWriter結構體
// buffered input and output// ReadWriter stores pointers to a Reader and a Writer.// It implements io.ReadWriter.type ReadWriter struct {*Reader*Writer}
所有的方法,
func NewReadWriter(r *Reader, w *Writer) *ReadWriter
=======END=======