go--读取文件的方式

package main

import (
    "bufio"
    "fmt"
    "io"
    "io/ioutil"
    "os"
    "testing"
)

const fileName = "README.md"

//按照处理的字节数读取
func TestReadFilr(t *testing.T) {
    file, err := os.Open(fileName)
    if err != nil {
        t.Error(err)
    }
    buffer := make([]byte, 1024)
    for {
        if a, b := file.Read(buffer); a != 0 && b != io.EOF {
            fmt.Println(b)
        } else {
            return
        }
    }
}

// 一次性读取
func TestReadFile2(t *testing.T) {
    if d, err := ioutil.ReadFile(fileName); err == nil {
        str := string(d)
        fmt.Println(str)
    } else {
        t.Error(err)
    }
}

//TestReadFileLBL line by line
func TestReadFileLBL(t *testing.T) {
    if file, err := os.Open(fileName); err == nil {
        buffer := bufio.NewScanner(file)
        position := 0
        for buffer.Scan() {
            desc := fmt.Sprintf("%d >> %s", position, buffer.Text())
            fmt.Println(desc)
        }
    }

}
    原文作者:FIZLIN
    原文地址: https://segmentfault.com/a/1190000016780456
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞