There are generally two ways to read files in Go. One way is to use the functions os
under the package os.open
for streaming reading, and the other way is to use the functions ioutil
of the package ioutil.ReadFile
for reading. The difference between the two is that the latter will read the file at one time. The contents are all loaded into memory.
Since os.open
the function will return a file object, it needs to be coordinated bufio
or ioutil
used.
The following are examples of specific use:
package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
)
func main() {
file := "H:\\go\\main\\1.txt"
ReadByIoUntil(file)
ReadByOs(file)
}
func ReadByIoUntil(filename string) {
fmt.Println("-------通过ioutil.ReadFile读取---------")
data, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Fprintf(os.Stderr, "error reading file: %v\n", err)
}
fmt.Println(string(data))
}
func ReadByOs(filename string) {
fmt.Println("-------通过os.Open读取---------")
f, err := os.Open(filename)
if err != nil {
fmt.Fprintf(os.Stderr, "error reading file: %v\n", err)
}
//采用bufio读取文件内容
input := bufio.NewScanner(f)
for input.Scan() {
fmt.Println(input.Text())
}
//采用ioutil读取文件内容,由于流是一次性的,所以上面的代码输出后,下面的Println将不再打印任何东西
contents, err := ioutil.ReadAll(f)
fmt.Println(contents)
f.Close()
}