一.输入流

  • 流(stream)是应用程序和外部资源进行数据交互的纽带
  • 流分为输入流和输出流,输入和输出都是相对于程序,把外部数据传入到程序中叫做输入,反之叫做输出流
  • 输入流(Input Stream),输入流(Output Stream) 平时所说的I/O流
  • 在Go语言标准库中io包下是Reader接口表示输入流,只要实现这个接口就属于输入流
    1. // Reader is the interface that wraps the basic Read method.
    2. //
    3. // Read reads up to len(p) bytes into p. It returns the number of bytes
    4. // read (0 <= n <= len(p)) and any error encountered. Even if Read
    5. // returns n < len(p), it may use all of p as scratch space during the call.
    6. // If some data is available but not len(p) bytes, Read conventionally
    7. // returns what is available instead of waiting for more.
    8. //
    9. // When Read encounters an error or end-of-file condition after
    10. // successfully reading n > 0 bytes, it returns the number of
    11. // bytes read. It may return the (non-nil) error from the same call
    12. // or return the error (and n == 0) from a subsequent call.
    13. // An instance of this general case is that a Reader returning
    14. // a non-zero number of bytes at the end of the input stream may
    15. // return either err == EOF or err == nil. The next Read should
    16. // return 0, EOF.
    17. //
    18. // Callers should always process the n > 0 bytes returned before
    19. // considering the error err. Doing so correctly handles I/O errors
    20. // that happen after reading some bytes and also both of the
    21. // allowed EOF behaviors.
    22. //
    23. // Implementations of Read are discouraged from returning a
    24. // zero byte count with a nil error, except when len(p) == 0.
    25. // Callers should treat a return of 0 and nil as indicating that
    26. // nothing happened; in particular it does not indicate EOF.
    27. //
    28. // Implementations must not retain p.
    29. type Reader interface {
    30. Read(p []byte) (n int, err error)
    31. }

二.代码演示

  • 可以使用strings包下的NewReader创建字符串流

    1. r := strings.NewReader("hello 世界")
    2. b := make([]byte, r.Size())//创建字节切片,存放流中数据,根据流数据大小创建切片大小
    3. n, err := r.Read(b)//把流中数据读取到切片中
    4. if err != nil {
    5. fmt.Println("读取失败,", err)
    6. return
    7. }
    8. fmt.Println("读取数据长度,", n)
    9. fmt.Println("流中数据",string(b))//以字符串形式输入切片中数据
  • 最常用的是文件流,把外部文件中数据读取到程序中

    1. f, err := os.Open("D:/go.txt")//打开文件
    2. defer f.Close()
    3. if err != nil {
    4. fmt.Println("文件读取失败,", err)
    5. return
    6. }
    7. fileInfo, err := f.Stat()//获取文件信息
    8. if err != nil {
    9. fmt.Println("文件信息获取失败,", err)
    10. return
    11. }
    12. b := make([]byte, fileInfo.Size())//根据文件中数据大小创建切片
    13. _, err = f.Read(b)//读取数据到切片中
    14. if err != nil {
    15. fmt.Println("文件流读取失败:", err)
    16. return
    17. }
    18. fmt.Println("文件中内容为:", string(b))//以字符串形式输入切片中数据