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
+16.8k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+15.9k Golang :Trim white spaces from a string
+7.3k Golang : Reverse a string with unicode
+13.6k Golang : How to convert a number to words
+12.4k Golang : How to calculate the distance between two coordinates using Haversine formula
+5.4k Javascript : How to replace HTML inside <div>?
+5.1k Golang : What is StructTag and how to get StructTag's value?
+21.4k Golang : Convert seconds to minutes and remainder seconds
+7.9k Golang : Implementing class(object-oriented programming style)
+8.9k Golang : How to extract video or image files from html source code
+5.1k How to check with curl if my website or the asset is gzipped ?
+14.6k Golang : How do I get the local IP (non-loopback) address ?