一、一次性读取文件

package main

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

var filepath string

func main() {
	filepath = "test.log"
	c, err := ioutil.ReadFile(filepath)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(string(c))

}

二、逐行读取文件

package main

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

var filepath string

func main() {
	filepath = "test.log"
	file, err := os.Open(filepath)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer file.Close()
	line := bufio.NewReader(file)
	//遍历
	for {
		content, _, err := line.ReadLine()
		if err == io.EOF {
			break
		}
		fmt.Println(string(content))
		time.Sleep(time.Duration(2) * time.Second)
	}

}

三、按照字节数分段读取

package main

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

var filepath string

func main() {
	filepath = "test.log"
	file, err := os.Open(filepath)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer file.Close()
	bs := make([]byte, 4) //每次读取四个字节
	for {
		_, err := file.Read(bs)
		if err == io.EOF {
			break
		}
		fmt.Println(string(bs))
	}

}