Golang : bufio.NewReader.ReadLine to read file line by line
In the previous tutorial on how to read file line by line with bufio.NewScanner()
example. The previous example that use bufio.NewScanner()
will throw token too long error message if attempt to read a very large file. You can see the details here.
This tutorial will show you another way to read file line by line, but with bufio.NewReader()
and ReadLine()
method instead.
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
)
func main() {
flag.Parse()
filename := flag.Arg(0)
file, err := os.Open(filename)
if err != nil {
panic(err)
}
defer file.Close()
reader := bufio.NewReader(file)
for {
line, _, err := reader.ReadLine()
if err == io.EOF {
break
}
fmt.Printf("%s \n", line)
}
}
Go run this file with the filename as 1st parameter and it will print out each line to the screen.
Happy coding!
References :
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
+14.4k Golang : Get uploaded file name or access uploaded files
+17k Golang : How to generate QR codes?
+7.2k Golang : Transform lisp or spinal case to Pascal case example
+22k Golang : Upload big file (larger than 100MB) to AWS S3 with multipart upload
+12.7k Golang : Transform comma separated string to slice example
+13.1k Golang : Calculate elapsed years or months since a date
+14.5k Golang : Recombine chunked files example
+17.1k Golang : Set up source IP address before making HTTP request
+8k Javascript : How to check a browser's Do Not Track status?
+28.8k Golang : Read, Write(Create) and Delete Cookie example
+21.1k PHP : Convert(cast) int to double/float
+30.9k error: trying to remove "yum", which is protected