用户登录
用户注册

分享至

[Go] go等待读取最后一行的数据内容

  • 作者: 悍马11750148
  • 来源: 51数据库
  • 2021-08-17

这段代码是参照慕课网的视频教程,主要是f.seek(0, os.seek_end)移动到末尾,但是里面有个小问题,当打开的文件被重新清空内容的清空下,就再也不能到读取数据了,比如在开启读取后 echo ''>1.log 这样就再也读不到了,tail包是解决了这个问题的

package main

import (
    "bufio"
    "fmt"
    "io"
    "os"
    "strings"
    "time"
)

func main() {
    readchannel := make(chan string)
    go readfile(readchannel)
    for r := range readchannel {
        fmt.println(r)
    }
}
func readfile(readchannel chan string) {
    f, err := os.open("1.txt")
    if err != nil {
        panic(fmt.sprintf("open file error:%s", err.error()))
    }
    //移动到文件末尾
    f.seek(0, os.seek_end)
    reader := bufio.newreader(f)
    for {
        line, err := reader.readbytes('\n')
        fmt.println(err)
        if err == io.eof {
            time.sleep(time.second)
            continue
        } else if err != nil {
            panic("readbytes error:" + err.error())
        }

        linestr := strings.trimspace(string(line))
        readchannel <- linestr
    }
}

使用tail包测试时,有re-open文件

 

软件
前端设计
程序设计
Java相关