dousou1878 2018-07-09 03:35
浏览 248

bufio.NewScanner(r)从r调用Scan()排放缓冲区

I want to create 2 scanners from the same reader r. But when calling Scan() from the first scanner, it drains the buffer from r, so the second scanner is reading a zero buffer. Is that a common behavior? How to fix it so that the second scanner properly reads from the original r?

r := bytes.NewReader([]byte("ninebytes"))
fmt.Println(r.Len()) // 9
sc1 := bufio.NewScanner(r)
sc1.Scan()
fmt.Printf("scanner1: %s
", sc1.Text()) // scanner1: ninebytes

// i want create new scanner from r too
fmt.Println(r.Len()) // 0
sc2 := bufio.NewScanner(r)
sc1.Scan()
fmt.Printf("scanner2: %s
", sc2.Text()) // scanner2: 

Here's an example at play golang

This is what I'm trying to do: read a specific line from a file, but when calling the function a second time, r is drained.

func readLineScanner(r io.Reader, lineNum int) ([]byte, error) {
    sc := bufio.NewScanner(r)
    lastLine := 0
    for sc.Scan() {
        lastLine++
        if lastLine == lineNum {
            break
        }
    }
    return sc.Bytes(), sc.Err()
}
  • 写回答

1条回答 默认 最新

  • donglangtun1850 2018-07-09 19:46
    关注

    Reading a reader is in general a destructive action; particularly with http request bodies.

    Instead you can create a tee reader, which is modelled on the unix tee command.

    Link to the docs

    Modifying the example you've given:

    r := bytes.NewReader([]byte("ninebytes"))
    
    var buf bytes.Buffer
    tee := io.TeeReader(r, &buf)
    
    sc1 := bufio.NewScanner(tee)
    sc1.Scan()
    fmt.Printf("scanner1: %s
    ", sc1.Text())
    
    sc2 := bufio.NewScanner(&buf)
    sc2.Scan()
    fmt.Printf("scanner2: %s
    ", sc2.Text())
    

    Using a tee reader, as you read from r it will write a copy of those bytes to buf, which you can use again in the second scanner.

    评论

报告相同问题?

悬赏问题

  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条