bytes.buffer是一个缓冲byte类型的缓冲器存放着都是byte

Buffer 是 bytes 包中的一个 type Buffer struct{…}

A buffer is a variable-sized buffer of bytes with Read and Write methods. The zero value for Buffer is an empty buffer ready to use.

(是一个变长的 buffer,具有 Read 和Write 方法。 Buffer 的 零值 是一个 空的 buffer,可是能够使用)

Buffer 就像一个集装箱容器,能够存东西,取东西(存取数据)

  • 创建 一个 Buffer (事实上底层就是一个 []byte, 字节切片)
  • 向当中写入数据 (Write mtheods)
  • 从当中读取数据 (Write methods)

创建 Buffer缓冲器

var b bytes.Buffer  //直接定义一个 Buffer 变量,而不用初始化
b.Writer([]byte("Hello ")) // 能够直接使用 b1 := new(bytes.Buffer) //直接使用 new 初始化。能够直接使用
// 其他两种定义方式
func NewBuffer(buf []byte) *Buffer
func NewBufferString(s string) *Buffer

NewBuffer

// NewBuffer creates and initializes a new Buffer using buf as its initial
// contents. It is intended to prepare a Buffer to read existing data. It
// can also be used to size the internal buffer for writing. To do that,
// buf should have the desired capacity but a length of zero.
//
// In most cases, new(Buffer) (or just declaring a Buffer variable) is
// sufficient to initialize a Buffer.
func NewBuffer(buf []byte) *Buffer { return &Buffer{buf: buf} }
  • NewBuffer使用buf作为參数初始化Buffer,
  • Buffer既能够被读也能够被写
  • 假设是读Buffer。buf需填充一定的数据
  • 假设是写。buf需有一定的容量(capacity)。当然也能够通过new(Buffer)来初始化Buffer。另外一个方法NewBufferString用一个string来初始化可读Buffer,并用string的内容填充Buffer.
func IntToBytes(n int) []byte {
x := int32(n)
//创建一个内容是[]byte的slice的缓冲器
//与bytes.NewBufferString("")等效
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, x)
return bytesBuffer.Bytes()
}

NewBufferString

  • 方法NewBufferString用一个string来初始化可读Buffer。并用string的内容填充Buffer.
  • 使用方法和NewBuffer没有太大差别
// NewBufferString creates and initializes a new Buffer using string s as its
// initial contents. It is intended to prepare a buffer to read an existing
// string.
//
// In most cases, new(Buffer) (or just declaring a Buffer variable) is
// sufficient to initialize a Buffer.
func NewBufferString(s string) *Buffer {
return &Buffer{buf: []byte(s)}
}
func TestBufferString(){
buf1:=bytes.NewBufferString("swift")
buf2:=bytes.NewBuffer([]byte("swift"))
buf3:=bytes.NewBuffer([]byte{'s','w','i','f','t'})
fmt.Println("===========下面buf1,buf2,buf3等效=========")
fmt.Println("buf1:", buf1)
fmt.Println("buf2:", buf2)
fmt.Println("buf3:", buf3)
fmt.Println("===========下面创建空的缓冲器等效=========")
buf4:=bytes.NewBufferString("")
buf5:=bytes.NewBuffer([]byte{})
fmt.Println("buf4:", buf4)
fmt.Println("buf5:", buf5)
}

输出:

===========下面buf1,buf2,buf3等效=========

buf1: swift

buf2: swift

buf3: swift

===========下面创建空的缓冲器等效=========

buf4:

buf5:

向 Buffer 中写入数据

Write

把字节切片 p 写入到buffer中去。

// Write appends the contents of p to the buffer, growing the buffer as
// needed. The return value n is the length of p; err is always nil. If the
// buffer becomes too large, Write will panic with ErrTooLarge.
func (b *Buffer) Write(p []byte) (n int, err error) {
b.lastRead = opInvalid
m := b.grow(len(p))
return copy(b.buf[m:], p), nil
}
fmt.Println("===========下面通过Write把swift写入Learning缓冲器尾部=========")
newBytes := []byte("swift")
//创建一个内容Learning的缓冲器
buf := bytes.NewBuffer([]byte("Learning"))
//打印为Learning
fmt.Println(buf.String())
//将newBytes这个slice写到buf的尾部
buf.Write(newBytes)
fmt.Println(buf.String())

打印:

===========下面通过Write把swift写入Learning缓冲器尾部=========

Learning

Learningswift

WriteString

使用WriteString方法,将一个字符串放到缓冲器的尾部

// WriteString appends the contents of s to the buffer, growing the buffer as
// needed. The return value n is the length of s; err is always nil. If the
// buffer becomes too large, WriteString will panic with ErrTooLarge.
func (b *Buffer) WriteString(s string) (n int, err error) {
b.lastRead = opInvalid
m := b.grow(len(s))
return copy(b.buf[m:], s), nil
}
    fmt.Println("===========下面通过WriteString把swift写入Learning缓冲器尾部=========")
newString := "swift"
//创建一个string内容Learning的缓冲器
buf := bytes.NewBufferString("Learning")
//打印为Learning
fmt.Println(buf.String())
//将newString这个string写到buf的尾部
buf.WriteString(newString)
fmt.Println(buf.String())

打印:

===========下面通过Write把swift写入Learning缓冲器尾部=========

Learning

Learningswift

WriteByte

将一个byte类型的数据放到缓冲器的尾部

// WriteByte appends the byte c to the buffer, growing the buffer as needed.
// The returned error is always nil, but is included to match bufio.Writer's
// WriteByte. If the buffer becomes too large, WriteByte will panic with
// ErrTooLarge.
func (b *Buffer) WriteByte(c byte) error {
b.lastRead = opInvalid
m := b.grow(1)
b.buf[m] = c
return nil
}
fmt.Println("===========下面通过WriteByte把!写入Learning缓冲器尾部=========")
var newByte byte = '!'
//创建一个string内容Learning的缓冲器
buf := bytes.NewBufferString("Learning")
//打印为Learning
fmt.Println(buf.String())
//将newString这个string写到buf的尾部
buf.WriteByte(newByte)
fmt.Println(buf.String())

打印:

===========下面通过WriteByte把swift写入Learning缓冲器尾部=========

Learning

Learning!

WriteRune

将一个rune类型的数据放到缓冲器的尾部

// WriteRune appends the UTF-8 encoding of Unicode code point r to the
// buffer, returning its length and an error, which is always nil but is
// included to match bufio.Writer's WriteRune. The buffer is grown as needed;
// if it becomes too large, WriteRune will panic with ErrTooLarge.
func (b *Buffer) WriteRune(r rune) (n int, err error) {
if r < utf8.RuneSelf {
b.WriteByte(byte(r))
return 1, nil
}
n = utf8.EncodeRune(b.runeBytes[0:], r)
b.Write(b.runeBytes[0:n])
return n, nil
}
    fmt.Println("===========下面通过WriteRune把\"好\"写入Learning缓冲器尾部=========")
var newRune = '好'
//创建一个string内容Learning的缓冲器
buf := bytes.NewBufferString("Learning")
//打印为Learning
fmt.Println(buf.String())
//将newString这个string写到buf的尾部
buf.WriteRune(newRune)
fmt.Println(buf.String())

打印:

===========下面通过WriteRune把”好”写入Learning缓冲器尾部=========

Learning

Learning好

完整演示样例

package main

import (
"bytes"
"encoding/binary"
"fmt"
) func main() {
//newBuffer 整形转换成字节
var n int = 10000
intToBytes := IntToBytes(n)
fmt.Println("==========int to bytes========")
fmt.Println(intToBytes)
//NewBufferString
TestBufferString()
//write
BufferWrite()
//WriteString
BufferWriteString()
//WriteByte
BufferWriteByte()
//WriteRune
BufferWriteRune() } func IntToBytes(n int) []byte {
x := int32(n)
//创建一个内容是[]byte的slice的缓冲器
//与bytes.NewBufferString("")等效
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, x)
return bytesBuffer.Bytes()
} func TestBufferString(){
buf1:=bytes.NewBufferString("swift")
buf2:=bytes.NewBuffer([]byte("swift"))
buf3:=bytes.NewBuffer([]byte{'s','w','i','f','t'})
fmt.Println("===========下面buf1,buf2,buf3等效=========")
fmt.Println("buf1:", buf1)
fmt.Println("buf2:", buf2)
fmt.Println("buf3:", buf3)
fmt.Println("===========下面创建空的缓冲器等效=========")
buf4:=bytes.NewBufferString("")
buf5:=bytes.NewBuffer([]byte{})
fmt.Println("buf4:", buf4)
fmt.Println("buf5:", buf5)
} func BufferWrite(){
fmt.Println("===========下面通过Write把swift写入Learning缓冲器尾部=========")
newBytes := []byte("swift")
//创建一个内容Learning的缓冲器
buf := bytes.NewBuffer([]byte("Learning"))
//打印为Learning
fmt.Println(buf.String())
//将newBytes这个slice写到buf的尾部
buf.Write(newBytes)
fmt.Println(buf.String())
} func BufferWriteString(){
fmt.Println("===========下面通过Write把swift写入Learning缓冲器尾部=========")
newString := "swift"
//创建一个string内容Learning的缓冲器
buf := bytes.NewBufferString("Learning")
//打印为Learning
fmt.Println(buf.String())
//将newString这个string写到buf的尾部
buf.WriteString(newString)
fmt.Println(buf.String())
} func BufferWriteByte(){
fmt.Println("===========下面通过WriteByte把swift写入Learning缓冲器尾部=========")
var newByte byte = '!'
//创建一个string内容Learning的缓冲器
buf := bytes.NewBufferString("Learning")
//打印为Learning
fmt.Println(buf.String())
//将newString这个string写到buf的尾部
buf.WriteByte(newByte)
fmt.Println(buf.String())
} func BufferWriteRune(){
fmt.Println("===========下面通过WriteRune把\"好\"写入Learning缓冲器尾部=========")
var newRune = '好'
//创建一个string内容Learning的缓冲器
buf := bytes.NewBufferString("Learning")
//打印为Learning
fmt.Println(buf.String())
//将newString这个string写到buf的尾部
buf.WriteRune(newRune)
fmt.Println(buf.String())
}

向 Buffer 中读取数据

Read

给Read方法一个容器p。读完后。p就满了。缓冲器对应的降低了。返回的n为成功读的数量

// Read reads the next len(p) bytes from the buffer or until the buffer
// is drained. The return value n is the number of bytes read. If the
// buffer has no data to return, err is io.EOF (unless len(p) is zero);
// otherwise it is nil.
func (b *Buffer) Read(p []byte) (n int, err error) {}
func Read(){
bufs := bytes.NewBufferString("Learning swift.")
fmt.Println(bufs.String()) //声明一个空的slice,容量为8
l := make([]byte, 8)
//把bufs的内容读入到l内,由于l容量为8,所以仅仅读了8个过来
bufs.Read(l)
fmt.Println("::bufs缓冲器内容::")
fmt.Println(bufs.String())
//空的l被写入了8个字符,所以为 Learning
fmt.Println("::l的slice内容::")
fmt.Println(string(l))
//把bufs的内容读入到l内,原来的l的内容被覆盖了
bufs.Read(l)
fmt.Println("::bufs缓冲器被第二次读取后剩余的内容::")
fmt.Println(bufs.String())
fmt.Println("::l的slice内容被覆盖,由于bufs仅仅有7个了,因此最后一个g被留下来了::")
fmt.Println(string(l)) }

打印:

=======Read=======

Learning swift.

::bufs缓冲器内容::

swift.

::l的slice内容::

Learning

::bufs缓冲器被第二次读取后剩余的内容::

::l的slice内容被覆盖::

swift.g

ReadByte

返回缓冲器头部的第一个byte,缓冲器头部第一个byte被拿掉

// ReadByte reads and returns the next byte from the buffer.
// If no byte is available, it returns error io.EOF.
func (b *Buffer) ReadByte() (c byte, err error) {}
func ReadByte(){
bufs := bytes.NewBufferString("Learning swift.")
fmt.Println(bufs.String())
//读取第一个byte,赋值给b
b, _ := bufs.ReadByte()
fmt.Println(bufs.String())
fmt.Println(string(b))
}

打印:

=======ReadByte===

Learning swift.

earning swift.

L

ReadRune

ReadRune和ReadByte非常像

返回缓冲器头部的第一个rune,缓冲器头部第一个rune被拿掉

// ReadRune reads and returns the next UTF-8-encoded
// Unicode code point from the buffer.
// If no bytes are available, the error returned is io.EOF.
// If the bytes are an erroneous UTF-8 encoding, it
// consumes one byte and returns U+FFFD, 1.
func (b *Buffer) ReadRune() (r rune, size int, err error) {}
func ReadRune(){
bufs := bytes.NewBufferString("学swift.")
fmt.Println(bufs.String()) //读取第一个rune,赋值给r
r,z,_ := bufs.ReadRune()
//打印中文"学",缓冲器头部第一个被拿走
fmt.Println(bufs.String())
//打印"学","学"作为utf8储存占3个byte
fmt.Println("r=",string(r),",z=",z) }

ReadBytes

ReadBytes须要一个byte作为分隔符,读的时候从缓冲器里找第一个出现的分隔符(delim)。找到后,把从缓冲器头部開始到分隔符之间的全部byte进行返回,作为byte类型的slice,返回后。缓冲器也会空掉一部分

// ReadBytes reads until the first occurrence of delim in the input,
// returning a slice containing the data up to and including the delimiter.
// If ReadBytes encounters an error before finding a delimiter,
// it returns the data read before the error and the error itself (often io.EOF).
// ReadBytes returns err != nil if and only if the returned data does not end in
// delim.
func (b *Buffer) ReadBytes(delim byte) (line []byte, err error) {}
func ReadBytes(){
bufs := bytes.NewBufferString("如今開始 Learning swift.")
fmt.Println(bufs.String()) var delim byte = 'L'
line, _ := bufs.ReadBytes(delim)
fmt.Println(bufs.String())
fmt.Println(string(line))
}

打印:

=======ReadBytes==

如今開始 Learning swift.

earning swift.

如今開始 L

ReadString

ReadString须要一个byte作为分隔符。读的时候从缓冲器里找第一个出现的分隔符(delim),找到后,把从缓冲器头部開始到分隔符之间的全部byte进行返回,作为字符串。返回后,缓冲器也会空掉一部分

和ReadBytes相似

// ReadString reads until the first occurrence of delim in the input,
// returning a string containing the data up to and including the delimiter.
// If ReadString encounters an error before finding a delimiter,
// it returns the data read before the error and the error itself (often io.EOF).
// ReadString returns err != nil if and only if the returned data does not end
// in delim.
func (b *Buffer) ReadString(delim byte) (line string, err error) {}

ReadFrom

从一个实现io.Reader接口的r,把r里的内容读到缓冲器里。n返回读的数量

// ReadFrom reads data from r until EOF and appends it to the buffer, growing
// the buffer as needed. The return value n is the number of bytes read. Any
// error except io.EOF encountered during the read is also returned. If the
// buffer becomes too large, ReadFrom will panic with ErrTooLarge.
func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error) {}
func ReadFrom(){
//test.txt 内容是 "未来"
file, _ := os.Open("learngo/bytes/text.txt")
buf := bytes.NewBufferString("Learning swift.")
buf.ReadFrom(file) //将text.txt内容追加到缓冲器的尾部
fmt.Println(buf.String())
}

打印:

=======ReadFrom===

Learning swift.未来

Reset

将数据清空,没有数据可读

// Reset resets the buffer so it has no content.
// b.Reset() is the same as b.Truncate(0).
func (b *Buffer) Reset() { b.Truncate(0) }
func Reset(){
bufs := bytes.NewBufferString("如今開始 Learning swift.")
fmt.Println(bufs.String()) bufs.Reset()
fmt.Println("::已经清空了bufs的缓冲内容::")
fmt.Println(bufs.String())
}

打印:

=======Reset======

如今開始 Learning swift.

::已经清空了bufs的缓冲内容::

string

将未读取的数据返回成 string

// String returns the contents of the unread portion of the buffer
// as a string. If the Buffer is a nil pointer, it returns "<nil>".
func (b *Buffer) String() string {}

Golang之bytes.buffer的更多相关文章

  1. golang的bytes.buffer

    参考原文:go语言的bytes.buffer 一.创建缓冲期 bytes.buffer是一个缓冲byte类型的缓冲器 1.使用bytes.NewBuffer创建:参数是[]byte的话,缓冲器里就是这 ...

  2. Golang bytes.buffer详解

    原文:https://www.jianshu.com/p/e53083132a25 Buffer 介绍 Buffer 是 bytes 包中的一个 type Buffer struct{…} A buf ...

  3. golang bytes.Buffer Reset

    func t() { a := []'} buf := new(bytes.Buffer) buf.Write(a) b := buf.Bytes() fmt.Println(b) buf.Reset ...

  4. Golang学习 - bytes 包

    ------------------------------------------------------------ 对于传入 []byte 的函数,都不会修改传入的参数,返回值要么是参数的副本, ...

  5. golang的bytes.NewReader函数出现的问题

    在我试图装入一个300mb的数据时,发生了溢出. 我本以为不会出现这种问题的(内存和硬盘都够用),可见golang的bytes包还是设置了容量限制的. 虽然通常来说300mb的[]byte不管什么情况 ...

  6. Golang 使用Protocol Buffer 案例

    目录 1. 前言 2. Protobuf 简介 2.1 Protobuf 优点 2.2 Protobuf 缺点 2.3 Protobuf Golang 安装使用 3. Protobuf 通讯案例 3. ...

  7. golang语言中bytes包的常用函数,Reader和Buffer的使用

    bytes中常用函数的使用: package main; import ( "bytes" "fmt" "unicode" ) //byte ...

  8. [golang]内存不断增长bytes.makeSlice

    ------------------------------------------ 2015.7月更新 后面发现这里其实有一个sb的问题,在于内存回收和释放. 每个http请求,都会带一个http. ...

  9. 关于golang中IO相关的Buffer类浅析

    io重要的接口 在介绍buffer之前,先来认识两个重要的接口,如下边所示: type Reader interface { Read(p []byte) (n int, err error) } t ...

随机推荐

  1. PAT Basic 1054

    1054 求平均值 本题的基本要求非常简单:给定 N 个实数,计算它们的平均值.但复杂的是有些输入数据可能是非法的.一个“合法”的输入是 [−1000,1000] 区间内的实数,并且最多精确到小数点后 ...

  2. SQLServer数据库查看死锁、堵塞情况

    在压力测试过程中,不间断的按F5键执行上面的SQL语句,如果出现死锁或者堵塞现象,就会在执行结果中罗列出来.如果每次连续执行SQL,都有死锁或者堵塞出现,说明死锁或者堵塞的比较严重. --每秒死锁数量 ...

  3. Wp 导航到手机定位设置页面

    WP开放了很多选择器和启动器,找了半天没发现有打开定位设置页面的,找了好久终于找到了解决办法: await Windows.System.Launcher.LaunchUriAsync(new Uri ...

  4. python-selenium使用send_keys()方法写中文报错的解决方法

    问题描述: 自动化操作页面,输入中文姓名: # coding=utf-8 url = "http://dealer.bitauto.com/50002218/zuidijia/" ...

  5. P2341 受欢迎的牛

    受欢迎的牛 洛谷链接 题目大意: 有n头牛,牛会喜欢其他牛和自己,而喜欢是可以传递的,求被所有牛喜欢的牛的数量. 思路: 这是一道tarjan缩点的题目.被所有牛都喜欢的牛,一定会在一个强连通分量里. ...

  6. Java&Android代码规范

    项目中直接导入Square的代码风格文件.(不导入Google的原因是Square同时提供了Java和Android两套统一风格,Google只提供了一套) Square Code Styles Go ...

  7. DataTable排序

    DataRow[] rows = dt.Select("", "name asc");   DataTable t = dt.Clone();   t.Clea ...

  8. BZOJ 1297: [SCOI2009]迷路 [矩阵快速幂]

    Description windy在有向图中迷路了. 该有向图有 N 个节点,windy从节点 0 出发,他必须恰好在 T 时刻到达节点 N-1. 现在给出该有向图,你能告诉windy总共有多少种不同 ...

  9. You need to install the perl-doc package to use this program

    You need to install the perl-doc package to use this program 解决方案:apt-get install perl-doc

  10. VirtualBox 下主机与虚拟机以及虚拟机之间互通信配置

    引用链接:1)http://www.it165.net/os/html/201401/7063.html 2)http://www.cnblogs.com/sineatos/p/4489620.htm ...