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
+13.5k Golang : Save(pipe) HTTP response into a file
+25.6k Golang : How to check if a connection to database is still alive ?
+4.5k Golang : Detect words using using consecutive letters in a given string
+8.3k Golang : Terminate-stay-resident or daemonize your program?
+34k Golang : Get file last modified date and time
+9.4k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
+9.9k Golang : Natural string sorting example
+9.5k Golang : Select region of interest with mouse click and crop from image
+5.7k Get Facebook friends working in same company
+11.4k Golang : Get absolute path to binary for os.Exec function with exec.LookPath
+25.2k Golang : Encrypt and decrypt data with AES crypto
+19.1k Golang : Secure(TLS) connection between server and client