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!