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
+20.4k Golang : Convert PNG transparent background image to JPG or JPEG image
+9k Golang : How to get garbage collection data?
+5.7k Golang : Extract unicode string from another unicode string example
+11.8k Golang : Split strings into command line arguments
+16k Golang : Find out mime type from bytes in buffer
+4.9k PHP : See installed compiled-in-modules
+8.2k Golang : How to check variable or object type during runtime?
+6.1k Golang : Detect face in uploaded photo like GPlus
+6.6k Nginx : Password protect a directory/folder
+17.3k How to enable MariaDB/MySQL logs ?
+33.6k Golang : Proper way to set function argument default value