Golang: Read data from File ( part II)

In the last post, we have seen how we can read data from the file line by line.  
Sometimes if the file size small then you can read the whole file in one go.  In this example, we will be reading the whole file in one go. 

We will be using 'ReadFile' from 'ioutil' lib to read the file content. 


package main

import (
	"fmt"
	"io/ioutil"
)

func main() {
	readFile("file.path")
}

func readFile(filePath string) {
	//Try to read file contents
	data, err := ioutil.ReadFile(filePath)
	//Check if there is any error reading file contents.
	if err != nil {
		fmt.Println("Unable to read the file content. Error: ", err)
		return
	}
	//Convert the byte data read from file to string and print.
	fmt.Println(string(data))
}

Read also

No comments:

Post a Comment

Golang: Http POST Request with JSON Body example

Go standard library comes with "net/http" package which has excellent support for HTTP Client and Server.   In order to post JSON ...