Go Bufio Pack

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Go Bufio Pack

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 so Me help for textual I/O.

Bufio. Reader Fabric Body

// 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}

All the way,

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)

Using the example,

Package Mainimport ("bytes" "Bufio" "FMT") func main () {b1: = []byte ("Hello world!") RD: = bytes. Newreader (B1) buf: = Bufio. Newreader (RD)//The default buffer size is 4096fmt. Printf ("1.the number of bytes that can is read from the buffer=%d\n", buf. Buffered ()) B2: = Make ([]byte, 5) buf. Read (B2) println (String (b2)) fmt. Printf ("2.the number of bytes that can is read from the 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 is read from the buffer=%d\n", buf. Buffered ()) fmt. Println ("--------------") Rd2: = bytes. Newreader ([]byte ("Hello World")) Buf2: = Bufio. Newreader (RD2)//Peek Returns a slice of the cache that references the first n bytes of data in the cache,//the operation does not read the data, only references, and the referenced data is valid for the next read operation//. If the slice length is less than n, an error message is returned stating the reason. If n is greater than the total size of the cache, Errbufferfull is returned. 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 isRead 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 Structural body

// 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}

All the way,

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)

Method uses an example,

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 Structural body

Scanner provides a convenient interface for reading data such as//a file of newline-delimited lines of text. Successive calls to//the Scan method would 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 is defined in the this package for scanning a file into//lines, bytes, utf-8-encoded runes, and Space-deli mited 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 is 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 the data in Buf.err Error//Sticky error.empties int//Count of successive empty tokens.scancalled bool//Scan ha s been called; Buffer is in use.done bool//Scan have finished.}

All the way,

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

Method uses an example,

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 Structural Body

// buffered input and output// ReadWriter stores pointers to a Reader and a Writer.// It implements io.ReadWriter.type ReadWriter struct {*Reader*Writer}

All the way,

func NewReadWriter(r *Reader, w *Writer) *ReadWriter

=======end=======

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.