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
+5.8k Mac/Linux/Windows : Get CPU information from command line
+17.6k Golang : Get host name or domain name from IP address
+13.7k Golang : Get all local users and print out their home directory, description and group id
+14.8k Golang : Get sub string example
+32.4k Golang : How to check if slice or array is empty?
+5.7k PHP : Shuffle to display different content or advertisement
+3.7k Golang : How to pass data between controllers with JSON Web Token
+6.5k Golang : Handling Yes No Quit query input
+17.6k Golang : Populate dropdown with html/template example
+8.6k Golang : How to check if a website is served via HTTPS
+9k Android Studio : Simple input textbox and intercept key example
+6.2k Golang : How to handle file size larger than available memory panic issue