Go 读取文件的几种方式

Go 读取文件的几种方式

读取整个文件

方式 1

package main

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

func main() {
	file, err := os.Open("./index.go")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	content, err := ioutil.ReadAll(file)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(content))
}

方式 2

package main

import (
	"fmt"
	"io/ioutil"
)

func main() {
	filePath := "./index.go"
	content, err := ioutil.ReadFile(filePath)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(content))
}

按照字节数读取

package main

import (
	"fmt"
	"io"
	"os"
)

func main() {
	file, err := os.Open("./index.go")
	if err != nil {
		panic(err)
	}
	defer file.Close()
	chunks := make([]byte, 0)
	buffer := make([]byte, 1024)

	for {
		n, err := file.Read(buffer)
		if err == io.EOF {
			break
		}
		chunks = append(chunks, buffer[:n]...)
	}
	fmt.Println(string(chunks))
}

按行读取

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	file, err := os.Open("./index.go")
	if err != nil {
		panic(err)
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		fmt.Println(line)
	}
}