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
+5.4k Golang : Convert an executable file into []byte example
+4.4k Javascript : How to loop over and parse JSON data?
+13.8k Golang : How to check for empty array string or string?
+17.2k Golang : Write file with io.WriteString
+72.5k Golang : How to return HTTP status code?
+10.7k Golang : Detect user location with HTML5 geo-location
+4.1k Golang : Display packages names during compilation
+15.4k CodeIgniter/PHP : Create directory if does not exist example
+12.9k Golang : Check if a file exist or not
+7.9k Golang : Intercept and compare HTTP response code example
+6k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+15.4k Golang : Set up source IP address before making HTTP request