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
+24.8k Golang : Convert(cast) string to uint8 type and back to string
+6.6k SSL : How to check if current certificate is sha1 or sha2 from command line
+6.8k Golang : Error reading timestamp with GORM or SQL driver
+29.9k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions
+4.6k Unix/Linux : How to find out the hard disk size?
+5k Golang : Detect variable or constant type
+5k Golang : How to verify input is rune?
+12.5k Golang : Check if an integer is negative or positive
+5.5k Golang : Find the longest line of text example
+26.5k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+7.8k Golang : Simple histogram example
+4.7k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday