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
+9k Golang : Print how to use flag for your application example
+26.5k Get file path of temporary file in Go
+5.7k Get Facebook friends working in same company
+7.2k Golang : How To Use Panic and Recover
+23.2k Golang : GORM read from database example
+34.1k Golang : How to split or chunking a file to smaller pieces?
+10k Golang : Characters limiter example
+9k Golang : Use regular expression to get all upper case or lower case characters example
+11.2k Golang : Listen and Serve on sub domain example
+10k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+21.7k Golang : Randomly pick an item from a slice/array example
+7.9k Golang : HTTP Routing with Goji example