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)
}
}
}
有疑问加站长微信联系(非本文作者)