golang文件读取-按行读取

版权声明:http://blog.csdn.net/robertkun https://blog.csdn.net/robertkun/article/details/79163905

golang文件读取-按行读取

a.txt文件内容:

ABCDEFGHI
HELLO GOLANG

package main

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

func main() {
    fileName := "C:\\Robert\\日志分析\\tools_go\\vdn_sqlInterface\\a.txt"
    file, err := os.OpenFile(fileName, os.O_RDWR, 0666)
    if err != nil {
        fmt.Println("Open file error!", err)
        return
    }
    defer file.Close()

    stat, err := file.Stat()
    if err != nil {
        panic(err)
    }

    var size = stat.Size()
    fmt.Println("file size=", size)

    buf := bufio.NewReader(file)
    for {
        line, err := buf.ReadString('\n')
        line = strings.TrimSpace(line)
        fmt.Println(line)
        if err != nil {
            if err == io.EOF {
                fmt.Println("File read ok!")
                break
            } else {
                fmt.Println("Read file error!", err)
                return
            }
        }
    }
}

输出:
每次输出一行

file size= 23
ABCDEFGHI
HELLO GOLANG
File read ok!

阅读更多 登录后自动展开
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页