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