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
+14.7k Golang : Find location by IP address and display with Google Map
+7.6k Android Studio : Rating bar example
+7.3k Golang : get the current working directory of a running program
+5.8k Javascript : Generate random key with specific length
+9.5k Golang : Convert octal value to string to deal with leading zero problem
+5.3k Golang : Error handling methods
+5.7k Golang : Get missing location after unmarshal binary and gob decode time.
+19.9k Golang : Read directory content with os.Open
+16.4k Golang : Capture stdout of a child process and act according to the result
+6.2k Golang : Skip or discard items of non-interest when iterating example
+5.7k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+22.3k Golang : Calculate time different