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
+4.3k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+15.8k Golang : XML to JSON example
+5.6k Golang : How to validate ISBN?
+13.2k Golang : Overwrite previous output with count down timer
+7.2k How to show different content from website server when AdBlock is detected?
+5.5k Golang : Find the longest line of text example
+6.5k Golang : Detect sample rate, channels or latency with PortAudio
+16.5k Golang : Put UTF8 text on OpenCV video capture image frame
+13.1k Golang : ROT47 (Caesar cipher by 47 characters) example
+24.5k Golang : How to write CSV data to file
+15k Golang : How to extract links from web page ?
+5.3k Golang : Map within a map example