io 相关库函数参考
https://github.com/polaris1119/The-Golang-Standard-Library-by-Example/blob/master/chapter01/01.1.md
写文件
https://studygolang.com/articles/2073
多次读
https://blog.csdn.net/xingwangc2014/article/details/52319948
就是重复读数据的几种方法。总结一下这篇:
- 最简单的方法是读到内存中,然后怎么读都可以
b, err := ioutil.ReadAll(u)
r := bytes.NewReader(b)
r.Seek(0, 0)
return r
- 只读一部分,然后用MultiReader 把读过的部分和没读过的部分合在一起
b := make([]byte, 2)
_, err := u.Read(b)
r := io.MultiReader(bytes.NewReader(b), u)
return r
- io.TeeReader+pipe,并行读两次
pr, pw := io.Pipe()
tr := io.TeeReader(u, pw)
return pr,tr
- io.MultiWriter+pipe, 并行读多次
mp4R, mp4W := io.Pipe()
webmR, webmW := io.Pipe()
oggR, oggW := io.Pipe()
wavR, wavW := io.Pipe()
mw := io.MultiWriter(mp4W, webmW, oggW, wavW)
return mp4R,webmR,oggR,wavR
只抽取了读写的代码,同步和错误处理的代码请参考原文
buffer 的使用
参考:http://www.flysnow.org/2017/05/08/go-in-action-go-reader-writer.html
buffer 和 file 一样,同时有read 和write 的接口
package main
import (
"fmt"
"bytes"
"os"
"io"
)
func main(){
fmt.Println("buffer test")
var b bytes.Buffer
fmt.Println(b.Cap())
//string
b.WriteString("hello") // b as writer
fmt.Println(b.ReadString(255)) // b as reader
//bytes
b.Write([]byte("hello")) //b as writer
var bs =make([]byte,100)
b.Read(bs) // b as reader
fmt.Println(string(bs))
//interact with other io
//directly
io.Copy(os.Stdout,os.Stdin)
//b as man in middle
b.ReadFrom(os.Stdin) //b as writer
b.WriteTo(os.Stdout) //b as reader
}
自定义reader writer
https://www.cnblogs.com/jkko123/p/6952237.html
buffer 和 []byte 的一些函数
https://www.cnblogs.com/jkko123/p/7221544.html
网络IO 的例子
https://www.jianshu.com/p/8c33f7c84509
LimitReader 的例子1
r := strings.NewReader("Hello World!")
lr := io.LimitReader(r, 5)
n, err := io.Copy(os.Stdout, lr) // Hello