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
+24.1k Golang : Use regular expression to validate domain name
+13.7k Golang : Strings comparison
+5.6k Golang : Stop goroutine without channel
+41.1k Golang : How to check if a string contains another sub-string?
+9.6k Golang : Convert(cast) string to int64
+9.6k Golang : Extract or copy items from map based on value
+6.1k Golang : Extract unicode string from another unicode string example
+13.2k Golang : Handle or parse date string with Z suffix(RFC3339) example
+11.8k Golang : Calculations using complex numbers example
+8.3k Golang : Qt splash screen with delay example
+8.4k Golang : Configure Apache and NGINX to access your Go service example