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
+10.6k Generate Random number with math/rand in Go
+31k error: trying to remove "yum", which is protected
+5.1k Python : Find out the variable type and determine the type with simple test
+6.9k Golang : Output or print out JSON stream/encoded data
+12.5k Golang : Encrypt and decrypt data with x509 crypto
+10.3k Golang : Text file editor (accept input from screen and save to file)
+26.2k Mac/Linux and Golang : Fix bind: address already in use error
+7.4k Golang : How to fix html/template : "somefile" is undefined error?
+5.6k Golang : Display advertisement images or strings on random order
+7.5k Golang : How to iterate a slice without using for loop?
+6.3k Golang & Javascript : How to save cropped image to file on server
+11.7k Use systeminfo to find out installed Windows Hotfix(s) or updates