GO语言的IO方法实例小结

2019-11-10 10:32:26王冬梅

type PipeWriter

type PipeWriter struct {
    // contains filtered or unexported fields
}

(1)func (w *PipeWriter) Close() error关闭管道,关闭时正在进行的Read操作将返回EOF,若管道内仍有未读取的数据,后续仍可正常读取

import (
 "fmt"
 "io"
)

func main() {
 r, w := io.Pipe()
 go w.Write([]byte("hello word"))

 data := make([]byte, 10)
 n, err := r.Read(data)
 w.Close()
 if err == io.EOF {
  fmt.Println("executing read return EOF")
  fmt.Println("executing read reads number", n)
 }
 n, _ = r.Read(data)
 fmt.Println(string(data))          //hello word
 fmt.Println("next read number", n) //next read number 0
}

(2)func (w *PipeWriter) CloseWithError(err error) error这个函数和read里边的CloseWithError是大同小异的,关闭管道,关闭时正在进行的Read操作将返回参数传入的异常,若管道内仍有未读取的数据,后续仍可正常读取

import (
 "errors"
 "fmt"
 "io"
)

func main() {
 r, w := io.Pipe()
 go w.Write([]byte("hello widuu"))
 newerr := errors.New("your daye 突然关闭了")
 w.CloseWithError(newerr)
 data := make([]byte, 10)
 _, err := r.Read(data)
 if err != nil {
  fmt.Println(err) //your daye 突然关闭了
 }
}

(3)func (w *PipeWriter) Write(data []byte) (n int, err error)终于来打write了,这个是把字节切片写入管道,返回的是写入字节数和error,前边用到的太多了,随便哪一个吧

import (
 "fmt"
 "io"
)

func main() {
 r, w := io.Pipe()
 go w.Write([]byte("hello widuu")) //写入的是[]byte,注意官方文档写的是,写入管道阻塞,一直到所有数据的读取结束
 data := make([]byte, 11)
 n, _ := r.Read(data)
 fmt.Println(string(data))     //hello widuu
 fmt.Println("read number", n) //read number 10
}


type Reader


type Reader interface {
    Read(p []byte) (n int, err error)
}

(1)func LimitReader(r Reader, n int64) Reader,我们之前就说了Reader这个结构,其实这就是对Reader的一次封装,限定了它读取字节数,其实他实现的就是io.LimitedReader{}这个结构

import (
 "fmt"
 "io"
 "os"
 "reflect"
)

func main() {
 f, _ := os.Open("test.txt")
 defer f.Close()
 reader := io.LimitReader(f, 5)