Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




GO - READING FILE


So, in the previous tutorial, we have created a file named 'myfirstfile.txt', with the below contents,


java_Collections

Now, To delete a File, we need to import the 'io/ioutil' package.


Let us see, how can we read the above file in Go.


How to read the entire file?


Example :



package main
import "fmt"
import "io/ioutil"
     
func main() { 
     
    str, error := ioutil.ReadFile("myfirstfilego.txt") 
    if (error != nil) { 
        fmt.Println("Error occurred while reading the file.") 
    } 
        
    fmt.Printf("%s",str)
        
}


Output :



 In a huge pond,
 there lived many fish.
 They were arrogant and
 never listened to anyone.In this pond,
 there also lived
 a kind-hearted crocodile.
  1. So we have used the 'ReadFile()' Function from the 'ioutil' package to read the entire contents of the file.

    str = ioutil.ReadFile("myfirstfilego.txt")


    And initialised the contents of the file in a variable, 'str'. The contents of the file is stored in bytes in 'str'.
  2. After that we have used the 'fmt.Printf' statement to print the contents of 'str' after converting it to String.

    fmt.Printf("%s",str)