Golang : Read file and convert content to string
Problem :
You want to read a file content and convert the content into string.
Solution :
Read the file with ioutil.ReadFile() function. The file content will be in []byte and you just convert the byte into string
s := string(filecontent)
Below is a full example :
package main
import (
"fmt"
"io/ioutil"
)
func main() {
file, err := ioutil.ReadFile("testfile.txt")
if err != nil {
fmt.Println(err)
return
}
// out the file content
fmt.Println(string(file))
}
References :
http://golang.org/pkg/io/ioutil/#ReadFile
https://www.socketloop.com/tutorials/golang-read-file-with-ioutil
See also : Golang : Read a file line by line
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
+8.9k Golang : Gonum standard normal random numbers example
+12k Golang : Simple client-server HMAC authentication without SSL example
+9k Golang : How to check if a string with spaces in between is numeric?
+4.6k Which content-type(MIME type) to use for JSON data
+52k Golang : How to get struct field and value by name
+8k Golang : Metaprogramming example of wrapping a function
+19.6k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+30.5k Golang : Interpolating or substituting variables in string examples
+12.4k Golang : Sort and reverse sort a slice of bytes
+9.5k Golang : interface - when and where to use examples
+16.8k Golang : Covert map/slice/array to JSON or XML format
+9.9k Golang : Compare files modify date example