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
+4.3k Mac OSX : Get disk partitions' size, type and name
+13.6k Golang: Pad right or print ending(suffix) zero or spaces in fmt.Printf example
+21.6k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."
+7.8k Golang : Append and add item in slice
+7.5k Setting $GOPATH environment variable for Unix/Linux and Windows
+9.2k Golang : Get all countries currencies code in JSON format
+14.7k JavaScript/JQuery : Detect or intercept enter key pressed example
+16.1k CodeIgniter/PHP : Create directory if does not exist example
+21.4k Golang : Setting up/configure AWS credentials with official aws-sdk-go
+9.9k Golang : How to profile or log time spend on execution?
+26.8k Golang : Convert CSV data to JSON format and save to file
+21.8k Golang : Print leading(padding) zero or spaces in fmt.Printf?