Go bufio包

xxggy · · 2192 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

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          []byte
	rd           io.Reader // reader provided by the client
	r, w         int       // buf read and write positions
	err          error
	lastByte     int
	lastRuneSize int
}

所有的方法,

func NewReader(rd io.Reader) *Reader
func NewReaderSize(rd io.Reader, size int) *Reader
func (b *Reader) Buffered() int
func (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() error
func (b *Reader) UnreadRune() error
func (b *Reader) WriteTo(w io.Writer) (n int64, err error)

使用示例,

package main

import (
	"bytes"
	"bufio"
	"fmt"
)

func main() {
	b1 := []byte("hello world!")
	rd := bytes.NewReader(b1)
	buf := bufio.NewReader(rd) //默认的缓冲区大小是 4096

	fmt.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 error
	buf []byte
	n   int
	wr  io.Writer
}

所有的方法,

func NewWriter(w io.Writer) *Writer
func NewWriterSize(w io.Writer, size int) *Writer
func (b *Writer) Available() int
func (b *Writer) Buffered() int
func (b *Writer) Flush() error
func (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) error
func (b *Writer) WriteRune(r rune) (size int, err error)
func (b *Writer) WriteString(s string) (int, error)

方法使用示例,

package main

import (
	"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) *Scanner
func (s *Scanner) Buffer(buf []byte, max int)
func (s *Scanner) Bytes() []byte
func (s *Scanner) Err() error
func (s *Scanner) Scan() bool
func (s *Scanner) Split(split SplitFunc)
func (s *Scanner) Text() string

方法使用示例,

package main

import (
	"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=======


有疑问加站长微信联系(非本文作者)

本文来自:开源中国博客

感谢作者:xxggy

查看原文:Go bufio包

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2192 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传