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.4k Clean up Visual Studio For Mac installation failed disk full problem
+12.2k Golang : Get month name from date example
+7.6k Golang : Mapping Iban to Dunging alphabets
+21.9k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."
+4.8k Javascript : How to get width and height of a div?
+6.9k Golang : How to setup a disk space used monitoring service with Telegram bot
+12.6k Golang : Remove or trim extra comma from CSV
+9.3k Golang : Play .WAV file from command line
+7.4k Golang : Rot13 and Rot5 algorithms example
+10.2k Golang : Detect number of faces or vehicles in a photo
+5.7k Unix/Linux : How to test user agents blocked successfully ?
+13.8k Golang : How to determine if a year is leap year?