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
+7.3k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+10.8k Golang : Select region of interest with mouse click and crop from image
+11.5k Golang : Characters limiter example
+5.2k Golang : Constant and variable names in native language
+7.6k Golang : Get YouTube playlist
+19.2k Golang : Clearing slice
+5.6k Gogland : Datasource explorer
+13.5k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+10.1k Golang : Ordinal and Ordinalize a given number to the English ordinal numeral
+18.8k Golang : Get download file size
+6.8k Golang : How to determine if request or crawl is from Google robots