package main

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

// 带缓存方式的读取文件
func readFileBuffer() {
	filePath := "/test/file/read/index.html"
	file, err := os.Open(filePath)
	if err != nil {
		fmt.Println("read file err", err)
	}
	// 关闭文件句柄
	defer file.Close()
	// 带缓存方式读取文件
	reader := bufio.NewReader(file)
	// 循环的读取文件内容
	for {
		content, err := reader.ReadString('\n')
		if err == io.EOF {
			break // 读取到文件的末尾
		}
		fmt.Printf("%v", content)
	}
}

// 一次性读取所有文件内容
// 该方式适合于读取文件内容比较小的
func readAllFile() {
	filePath := "/test/file/read/index.html"
	content, err := os.ReadFile(filePath)
	if err != nil {
		fmt.Println("read all file err", err)
	}
	// 该方式读取后,返回的是一个[]byte
	fmt.Printf("%v", string(content))
}

// 以io/ioutil读取文件
func readFileIoUtil() {
	filePath := "/test/file/read/index.html"
	// 返回一个 []byte 切片数据
	content, err := ioutil.ReadFile(filePath)
	if err != nil {
		fmt.Printf("read file err, %v\n", err)
	}
	fmt.Printf("read file success")
	fmt.Printf("%v", string(content))
}

// 文件的读取操作
func main() {
	readFileBuffer()
	readAllFile()
	readFileIoUtil()
}