Go-lang Lesson: Reading a file

This is simple example how to read a text file in the Go language.

package main

import (
    "os"
    "fmt"
    "bufio"
)

func main()  {
    f, err :=os.Open("/Users/ojitha/Documents/workspace/goex1/src/github.com/ojitha/examples/test.txt")
    if err != nil {
        fmt.Fprint(os.Stderr, err)
    } else {
        countLines(f)
    }
    f.Close()

}

func countLines(f *os.File)  {
    input := bufio.NewScanner(f)
    for input.Scan(){
        fmt.Printf(input.Text()+"\n")
    }
}

test.txt is the text file. This program will display all the contents of the text file. If error of opening file display an error instead of file contents.

Comments

Popular posts from this blog

How To: GitHub projects in Spring Tool Suite

Spring 3 Part 7: Spring with Databases

Parse the namespace based XML using Python