[]byte 转 io.Reader

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package main

import (
"bytes"
"fmt"
"log"
)

func main() {
data := []byte("Hello AlwaysBeta")

// byte slice to bytes.Reader, which implements the io.Reader interface
reader := bytes.NewReader(data)

// read the data from reader
buf := make([]byte, len(data))
if _, err := reader.Read(buf); err != nil {
log.Fatal(err)
}

fmt.Println(string(buf))
}

io.Reader 转 []byte

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package main

import (
"bytes"
"fmt"
"strings"
)

func main() {
ioReaderData := strings.NewReader("Hello AlwaysBeta")

// creates a bytes.Buffer and read from io.Reader
buf := &bytes.Buffer{}
buf.ReadFrom(ioReaderData)

// retrieve a byte slice from bytes.Buffer
data := buf.Bytes()

// only read the left bytes from 6
fmt.Println(string(data[6:]))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package main

import (
"bytes"
"fmt"
"os"
)

func main() {
// 创建 Buffer 暂存空间,并将一个字符串写入 Buffer
// 使用 io.Writer 的 Write 方法写入
var buf bytes.Buffer
buf.Write([]byte("hello world , "))

// 用 Fprintf 将一个字符串拼接到 Buffer 里
fmt.Fprintf(&buf, " welcome to golang !")

// 将 Buffer 的内容输出到标准输出设备
buf.WriteTo(os.Stdout)
}

o.Reader 接口:io.Reader 接口要求实现 Read(p []byte) (n int, err error) 方法,返回读取的字节数和错误信息。*bytes.Reader 就是通过实现这个方法来允许对 []byte 进行按块读取。