go--读取文件的方式

栏目: Go · 发布时间: 7年前

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)
        }
    }

}

以上所述就是小编给大家介绍的《go--读取文件的方式》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Music Recommendation and Discovery

Music Recommendation and Discovery

Òscar Celma / Springer / 2010-9-7 / USD 49.95

With so much more music available these days, traditional ways of finding music have diminished. Today radio shows are often programmed by large corporations that create playlists drawn from a limited......一起来看看 《Music Recommendation and Discovery》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

html转js在线工具
html转js在线工具

html转js在线工具