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
+6.7k Golang : Generate human readable password
+8.8k Golang : Check if user agent is a robot or crawler example
+18.6k Golang : How to get time from unix nano example
+16.6k Golang : Put UTF8 text on OpenCV video capture image frame
+10.2k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+10.1k How to test Facebook App on localhost ?
+12.9k Golang : Check if a file exist or not
+8k Golang : Populate or initialize struct with values example
+17.2k Golang : How to get hour, minute, second from time?
+6.8k Golang : Error reading timestamp with GORM or SQL driver
+5.8k Mac/Linux/Windows : Get CPU information from command line
+5.7k Golang : Calculate pivot points for a cross