文件 I/O,特别是对文件的读写是编程语言中重要的功能。通常,我们需要逐行读取文件。
bufioio.Readerio.Writer
os.Open()D:\\go_work\\test.txt
bufio.NewScanner(file)rScannerScanLines
ScannerScanScannertokenScan
ScannerErr()Scannerio.EOFErrnil
Go 逐行读取文件的完整代码
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
// open the file
file, err := os.Open("D:\\go_work\\test.txt")
// handle errors while opening
if err != nil {
log.Fatalf("Error when opening file: %s", err)
}
defer file.Close()
fileScanner := bufio.NewScanner(file)
// read line by line
for fileScanner.Scan() {
fmt.Println(fileScanner.Text())
}
// handle first encountered error while reading
if err := fileScanner.Err(); err != nil {
log.Fatalf("Error while reading file: %s", err)
}
}
配置 Scanner 行为
ScannerSplitSplitFuncScannerSplitFuncScanLines
例如,我们可以使用单词进行拆分,如下面的代码片段所示:
scanner.Split(bufio.ScanWords) //configure how the scanner behaves