Skip to main content

golang readline

· 2 min read

In Go 1.1 and newer the most simple way to do this is with a bufio.Scanner. Here is a simple example that reads lines from a file:

从Go 1.1开始,最新也是最简洁的方法就是用bufio.Scanner, 下面的例子将展示逐行读取

package main

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

func main() {
file, err := os.Open("/path/to/file.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()

scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Println(scanner.Text())
}

if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}

This is the cleanest way to read from a Reader line by line.

这是最好的方式从Reader中逐行读取

There is one caveat: Scanner will error with lines longer than 65536 characters. If you know your line length is greater than 64K, use the Buffer() method to increase the scanner’s capacity:

警告:如果单行超过 65536 个字符,那么Scanner就会出问题。 如果你单行超过 65536 个字符, 你应该重写Reader.Read()

参考: https://stackoverflow.com/questions/8757389/reading-a-file-line-by-line-in-go#16615559#753

当单行字节超过65535个字节(也就是64k)的时候,请使用Buffer()方法来增加scanner的容量

scanner := bufio.NewScanner(file)

const maxCapacity = longLineLen // your required line length
buf := make([]byte, maxCapacity)
scanner.Buffer(buf, maxCapacity)

for scanner.Scan() {}