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缓冲器

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

NewBuffer

  1. // NewBuffer creates and initializes a new Buffer using buf as its initial
  2. // contents. It is intended to prepare a Buffer to read existing data. It
  3. // can also be used to size the internal buffer for writing. To do that,
  4. // buf should have the desired capacity but a length of zero.
  5. //
  6. // In most cases, new(Buffer) (or just declaring a Buffer variable) is
  7. // sufficient to initialize a Buffer.
  8. 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.
  1. func IntToBytes(n int) []byte {
  2. x := int32(n)
  3. //创建一个内容是[]byte的slice的缓冲器
  4. //与bytes.NewBufferString("")等效
  5. bytesBuffer := bytes.NewBuffer([]byte{})
  6. binary.Write(bytesBuffer, binary.BigEndian, x)
  7. return bytesBuffer.Bytes()
  8. }

NewBufferString

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

输出:

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

buf1: swift

buf2: swift

buf3: swift

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

buf4:

buf5:

向 Buffer 中写入数据

Write

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

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

打印:

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

Learning

Learningswift

WriteString

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

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

打印:

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

Learning

Learningswift

WriteByte

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

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

打印:

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

Learning

Learning!

WriteRune

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

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

打印:

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

Learning

Learning好

完整演示样例

  1. package main
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "fmt"
  6. )
  7. func main() {
  8. //newBuffer 整形转换成字节
  9. var n int = 10000
  10. intToBytes := IntToBytes(n)
  11. fmt.Println("==========int to bytes========")
  12. fmt.Println(intToBytes)
  13. //NewBufferString
  14. TestBufferString()
  15. //write
  16. BufferWrite()
  17. //WriteString
  18. BufferWriteString()
  19. //WriteByte
  20. BufferWriteByte()
  21. //WriteRune
  22. BufferWriteRune()
  23. }
  24. func IntToBytes(n int) []byte {
  25. x := int32(n)
  26. //创建一个内容是[]byte的slice的缓冲器
  27. //与bytes.NewBufferString("")等效
  28. bytesBuffer := bytes.NewBuffer([]byte{})
  29. binary.Write(bytesBuffer, binary.BigEndian, x)
  30. return bytesBuffer.Bytes()
  31. }
  32. func TestBufferString(){
  33. buf1:=bytes.NewBufferString("swift")
  34. buf2:=bytes.NewBuffer([]byte("swift"))
  35. buf3:=bytes.NewBuffer([]byte{'s','w','i','f','t'})
  36. fmt.Println("===========下面buf1,buf2,buf3等效=========")
  37. fmt.Println("buf1:", buf1)
  38. fmt.Println("buf2:", buf2)
  39. fmt.Println("buf3:", buf3)
  40. fmt.Println("===========下面创建空的缓冲器等效=========")
  41. buf4:=bytes.NewBufferString("")
  42. buf5:=bytes.NewBuffer([]byte{})
  43. fmt.Println("buf4:", buf4)
  44. fmt.Println("buf5:", buf5)
  45. }
  46. func BufferWrite(){
  47. fmt.Println("===========下面通过Write把swift写入Learning缓冲器尾部=========")
  48. newBytes := []byte("swift")
  49. //创建一个内容Learning的缓冲器
  50. buf := bytes.NewBuffer([]byte("Learning"))
  51. //打印为Learning
  52. fmt.Println(buf.String())
  53. //将newBytes这个slice写到buf的尾部
  54. buf.Write(newBytes)
  55. fmt.Println(buf.String())
  56. }
  57. func BufferWriteString(){
  58. fmt.Println("===========下面通过Write把swift写入Learning缓冲器尾部=========")
  59. newString := "swift"
  60. //创建一个string内容Learning的缓冲器
  61. buf := bytes.NewBufferString("Learning")
  62. //打印为Learning
  63. fmt.Println(buf.String())
  64. //将newString这个string写到buf的尾部
  65. buf.WriteString(newString)
  66. fmt.Println(buf.String())
  67. }
  68. func BufferWriteByte(){
  69. fmt.Println("===========下面通过WriteByte把swift写入Learning缓冲器尾部=========")
  70. var newByte byte = '!'
  71. //创建一个string内容Learning的缓冲器
  72. buf := bytes.NewBufferString("Learning")
  73. //打印为Learning
  74. fmt.Println(buf.String())
  75. //将newString这个string写到buf的尾部
  76. buf.WriteByte(newByte)
  77. fmt.Println(buf.String())
  78. }
  79. func BufferWriteRune(){
  80. fmt.Println("===========下面通过WriteRune把\"好\"写入Learning缓冲器尾部=========")
  81. var newRune = '好'
  82. //创建一个string内容Learning的缓冲器
  83. buf := bytes.NewBufferString("Learning")
  84. //打印为Learning
  85. fmt.Println(buf.String())
  86. //将newString这个string写到buf的尾部
  87. buf.WriteRune(newRune)
  88. fmt.Println(buf.String())
  89. }

向 Buffer 中读取数据

Read

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

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

打印:

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

Learning swift.

::bufs缓冲器内容::

swift.

::l的slice内容::

Learning

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

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

swift.g

ReadByte

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

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

打印:

=======ReadByte===

Learning swift.

earning swift.

L

ReadRune

ReadRune和ReadByte非常像

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

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

ReadBytes

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

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

打印:

=======ReadBytes==

如今開始 Learning swift.

earning swift.

如今開始 L

ReadString

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

和ReadBytes相似

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

ReadFrom

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

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

打印:

=======ReadFrom===

Learning swift.未来

Reset

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

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

打印:

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

如今開始 Learning swift.

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

string

将未读取的数据返回成 string

  1. // String returns the contents of the unread portion of the buffer
  2. // as a string. If the Buffer is a nil pointer, it returns "<nil>".
  3. 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. sublime text 3搭建python 的ide

    感谢大佬-->原文链接 1. 打开Sublime text 3 安装package control Sublime Text 3 安装Package Control 2. 安装 SublimeR ...

  2. Web自动化Selenium2环境配置中Selenium IDE的安装

    下载的firefox32.0的版本,但是在附件组件中只有selenuim IDE button,本以为这个就是selenium IDE插件,自以为是的后果就是把自己坑了.并且像一些selenium I ...

  3. SQL server将查询到的多行结果,拼接成字符串(列转行)

    select stuff(( ,,'') as UserNamestr 注释:查询出tabname表中的UserName列的所有内容,并将内容拼接成UserNamestr

  4. 字符串格式化format很牛B

    python的format方法可谓相当强大,它可以接受不限个参数... 1.通过位置来格式化字符串,注意format传入的参数的位置要正确{0}对应第1个参数,{1}对应第2个参数... >&g ...

  5. python3--__call__拦截调用

    __call__拦截调用 当实例调用时,使用__call__方法.不,这不是循环定义:如果定义了,Python就会为实例应用函数调用表达式运行__call__方法.这样可以让类实例的外观和用法类似于函 ...

  6. 在VS2017中编写Python程序

    最近开始了python的学习,在搭建完python环境之后,在选择IDE的时候陷入了困境,首先选择的是PyCharm但是用着还是不习惯,毕竟用VS开发了几年了,突然换软件总感觉有点不适应,就想到了强大 ...

  7. 如何解决"The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path"

    今天我在eclipse上搭建新项目时,莫名其妙的出现这个错误,如下: The superclass "javax.servlet.http.HttpServlet" was not ...

  8. JSON与字符串互相转换的几种方法

    1 2 3 4 5 6 7 8 字符串转对象(strJSON代表json字符串)   var obj = eval(strJSON);   var obj = strJSON.parseJSON(); ...

  9. K-th Number(poj 2104)

    题意:静态第K大 #include<cstdio> #include<iostream> #include<cstring> #define N 200010 #d ...

  10. list或map 打印成json 方便调试

    private final Logger logger = Logger.getLogger(this.getClass()); logger.info(JSON.toJSONStringWithDa ...