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
+12.1k Golang : Determine if time variables have same calendar day
+7.7k Golang : How to handle file size larger than available memory panic issue
+20k Golang : Archive directory with tar and gzip
+4.2k Detect if Google Analytics and Developer Media are loaded properly or not
+9.6k Golang : Qt Yes No and Quit message box example
+52.1k Golang : How to get time in milliseconds?
+15.4k Golang : Delete certain files in a directory
+7.5k Golang : Calculate how many weeks left to go in a given year
+12.6k Golang : Extract part of string with regular expression
+5.1k Python : Convert(cast) bytes to string example
+13.5k Golang : Linear algebra and matrix calculation example
+18.4k Golang : Put UTF8 text on OpenCV video capture image frame