Golang : Read large file with bufio.Scanner cause token too long error
There are couple of ways to read files with Golang and one of the common way to read in file is with bufio.NewScanner() function. For example :
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
file, err := os.Open("somefile.dat")
if err != nil {
panic(err.Error())
}
defer file.Close()
reader := bufio.NewReader(file)
scanner := bufio.NewScanner(reader)
scanner.Split(bufio.ScanBytes)
for scanner.Scan() {
fmt.Println(scanner.Bytes())
}
if err := scanner.Err(); err != nil {
fmt.Println("error while reading :", err)
}
}
Most of the time, things should be fine and dandy. However, there will be cases when the program attempts to read in a very large file and it will throw out this error message :
"bufio.Scanner: token too long"
This error message was caused by the input token size that exceeded the bufio.MaxScanTokenSize
buffer size. The allocated size is MaxScanTokenSize = 64 * 1024
To read in large files, it is recommended to use bufio.Reader.ReadLine instead.
References :
See also : Golang : Scanf function weird error in Windows
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+22.3k Golang : How to read JPG(JPEG), GIF and PNG files ?
+7.2k Golang : Accessing dataframe-go element by row, column and name example
+15.4k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+16.2k Golang : Test floating point numbers not-a-number and infinite example
+12.8k Golang : Get terminal width and height example
+5.6k Unix/Linux : Get reboot history or check when was the last reboot date
+14.9k Golang : How do I get the local IP (non-loopback) address ?
+17.2k Golang : Multi threading or run two processes or more example
+7.9k Golang : Get all countries phone codes
+14k Golang : syscall.Socket example
+12.6k Golang : Listen and Serve on sub domain example
+12.1k Golang : Get month name from date example