[]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")
reader := bytes.NewReader(data)
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")
buf := &bytes.Buffer{} buf.ReadFrom(ioReaderData)
data := buf.Bytes()
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() { var buf bytes.Buffer buf.Write([]byte("hello world , "))
fmt.Fprintf(&buf, " welcome to golang !")
buf.WriteTo(os.Stdout) }
|
o.Reader 接口:io.Reader 接口要求实现 Read(p []byte) (n int, err error) 方法,返回读取的字节数和错误信息。*bytes.Reader 就是通过实现这个方法来允许对 []byte 进行按块读取。