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
+6.3k Golang : Process non-XML/JSON formatted ASCII text file example
+4.8k Fix Google Analytics Redundant Hostnames problem
+9.6k Golang : Extract or copy items from map based on value
+14.1k Golang : How to determine if a year is leap year?
+8k Swift : Convert (cast) String to Float
+7k Golang : How to solve "too many .rsrc sections" error?
+22.8k Generate checksum for a file in Go
+12.4k Golang : Display list of countries and ISO codes
+25.2k Golang : Create PDF file from HTML file
+11.6k Use systeminfo to find out installed Windows Hotfix(s) or updates
+38.2k Golang : Read a text file and replace certain words