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
+15.9k Golang : Defer function inside init()
+5.2k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+10.3k Get form post value in Go
+10.5k CodeIgniter : Import Linkedin data
+7.8k Golang : Build and compile multiple source files
+6.8k Golang : Gomobile init produce "iphoneos" cannot be located error
+8.7k PHP : Get coordinates latitude/longitude from string
+5.4k WARNING: UNPROTECTED PRIVATE KEY FILE! error message
+6.4k Golang : Rename part of filename
+14.7k Golang : Read integer from file into array
+20.4k Golang : Use TLS version 1.2 and enforce server security configuration over client
+6.2k Golang : Rot13 and Rot5 algorithms example