文档章节

Go bufio包

秋风醉了
 秋风醉了
发布于 2017/02/10 19:17
字数 1117
阅读 44
收藏 0

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=======

© 著作权归作者所有

上一篇: Go io包
下一篇: Go bytes包
秋风醉了
粉丝 250
博文 532
码字总数 405586
作品 0
朝阳
程序员
私信 提问
Golang实现简单tcp服务器01 -- 概述

概述 Golang作为一门近些年来非常风光的开发语言, 其实用范围很广, 图形界面, web框架, 图像引擎等等. 由于其语言特性简化了并发/多核的开发, 受到了很大的关注. 而使用它进行服务器开发, 也...

victoriest
2015/06/02
0
0
Go 1.1.2 正式发布

go1.1.2 (发布时间 2013/08/13) 主要包括 gc 和 cgo 等工具的BUG修复, 以及 bufio/runtime/syscall/time 等包的BUG修复. 如果是在 linux 32-bit (386 and arm) 平台使用了 syscall 包的 Getr...

chai2010
2013/08/13
5.4K
26
[翻译] effective go 之 Embedding

Embedding Go does not provide the typical, type-driven notion of subclassing, but it does have the ability to “borrow” pieces of an implementation by embedding types within a ......

pengfei_xue
2013/02/23
0
0
Golang 中 GBK 与 UTF-8 的转换

1.导⼊ mahonia 包,创建 gb18030 Decoder 进⾏行编码转换 http://code.google.com/p/mahonia 例子: import ( "bufio" "code.google.com/p/mahonia" "log" "os" ) func checkError(err inte......

L11758207
2013/03/04
0
1
Go语言开发Web服务器,进行压力测试,服务器挂掉了?

用Golang写了个测试程序如下: 运行,命令行下用ab进行压力测试,测试进行中Ctrl+C中断,程序就挂掉了,错误如下: D:\GoHTTP>GoHTTP.exe panic: AcceptEx tcp 0.0.0.0:8001: The specified...

李察德-泰森
2013/01/18
14.7K
38

没有更多内容

加载失败,请刷新页面

加载更多

Storm+Hbase广告实时统计

本文主要讲述使用Kafka+Strom+Hbase搭建的一套广告实时计算系统。其中服务器显示使用的是SpringBoot+Vue+ElementUI+EChats. 主要内容: 1.需求 2.日志格式 3.Hbase表格设计 4.编写Storm程序 ...

飓风2000
33分钟前
3
0
android,ContentProvider+ContentObserver+ContentResolver,用法。

这个是传智播客老师讲android开发时的一个图。 一、 PersonProvider继承ContentProvider,实现ContentProvider中的数据操作类。 ContentObserver——内容观察者,目的是观察(捕捉)特定Uri引起...

天王盖地虎626
38分钟前
2
0
解决markdown中的不换行问题

没有解决我的格式显示问题 https://blog.csdn.net/qq_23483671/article/details/79017609

南桥北木
43分钟前
2
0
产品上新|ZStack3.5.0正式发布啦!

海量产品资料传送门~ 一、ZStack全线产品下载通道汇总 社区版(免费): https://www.zstack.io/product/zstack_open_source/ 企业版下载: https://www.zstack.io/product/zstack_enterpris...

ZStack社区版
46分钟前
2
0
mysql 大表分页查询 翻页 优化方案

mysql分页查询是先查询出来所有数据,然后跳过offset,取limit条记录,造成了越往后的页数,查询时间越长 一般优化思路是转换offset,让offset尽可能的小,最好能每次查询都是第一页,也就是...

花树堆雪
49分钟前
12
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部