type Reader
func NewReader(b []byte) *Reader
NewReader创建一个从s读取数据的Reader。
func (r *Reader) Len() int
Len返回r包含的切片中还没有被读取的部分。
func (r *Reader) Read(b []byte) (n int, err error)
将对象数据读入b 中,返回读取的字节和遇到的遇到的错误
func (r *Reader) ReadByte() (b byte, err error)
从自身读出一个字节,读取一次并且把指针的值往后移动一位,返回读出的字节数和遇到的错误
func (r *Reader) UnreadByte() error
内部指针往前移动一位
func (r *Reader) ReadRune() (ch rune, size int, err error)
用于从自身读取一个 UTF-8 编码的读取到ch中并且返回长度和遇到的错误
func (r *Reader) Seek(offset int64, whence int) (int64, error)
移动数的读写指针
whence whence 为 0 (io.SeekStart) 表示从数据开头移动指针
whence whence 为 1 (io.SeekCurrent) 表示从数据当前位置移动指针
whence whence 为 1 (io.SeekEnd) 表示从数据结束位置移动指针
offset 为指针移动的偏移量
返回新的指针位置和遇到的错误
代码:
package main
import (
"bytes"
"fmt"
"io"
)
func main() {
b := []byte("abcdef")
c := b
e := []byte("1234")
f := []byte("世界")
//d := b
//得到字符长度 打印6
fmt.Println(len(b))
r := bytes.NewReader(b[2:])
//返回切片中没有被读取的部分
//打印 4
fmt.Println(r.Len())
//将对象的数据读入p中,返回读取的字节数和遇到的错误
n,_ := r.Read(e)
//打印 4 cdef
fmt.Println(n,string(e))
//重置指针,因为有read操作了之后,指针被指到了末尾
r.Seek(0,0)
//依次每次获取一个字符
bb,_ := r.ReadByte()
//打印 c
fmt.Printf("%c\n",bb)
//返回上一个字符
r.UnreadByte()
bb,_ = r.ReadByte()
//打印 c 因为有 UnreadByte 返回上一个字符操作
fmt.Printf("%c\n",bb)
r2 := bytes.NewReader(c)
//返回读取的字符,读取字符的长度
ch,s,_ := r2.ReadRune()
//打印 a,1 读取第一个字符 读取了一个长度
fmt.Printf("%c,%d\n",ch,s)
//设置 汉字
r3 := bytes.NewReader(f)
ch,s,_ = r3.ReadRune()
//打印 世 3
fmt.Printf("%c,%d\n",ch,s)
//移动位置指针到开始位置
r2.Seek(0,io.SeekStart)
bb,_ = r2.ReadByte()
//移到了开始位置,打印 a
fmt.Printf("%c",bb)
}