Go语言提供了方便的API来读取文件,本文将通过示例代码来详细讲解读取文件的过程。
打开文件
os.Open*File
func Open(name string) (*File, error)
nameerror
示例代码:
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.Open("example.txt")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
// do something with the file
}
example.txtdefer
读取文件
*File
读取全部内容
ioutil.ReadAll[]byte
func ReadAll(r io.Reader) ([]byte, error)
示例代码:
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
file, err := os.Open("example.txt")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
content, err := ioutil.ReadAll(file)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("File content: %s", content)
}
example.txt
Golang逐行读取文件内容
bufioNewScanner*bufio.Scanner
func NewScanner(r io.Reader) *Scanner
示例代码:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
file, err := os.Open("example.txt")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
fmt.Println(line)
}
if err := scanner.Err(); err != nil {
fmt.Println(err)
return
}
}
example.txt