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
+12.7k Golang : Get uploaded file name or access uploaded files
+10.2k Golang : Secure file deletion with wipe example
+13.5k Golang : How to check if IP address is in range
+16.3k Golang : Upload/Receive file progress indicator
+12.6k Golang : How to pass map to html template and access the map's elements
+10.9k Golang : Add ASCII art to command line application launching process
+5.7k Golang : Output or print out JSON stream/encoded data
+27.8k Golang : missing Git command
+6.8k Golang : Handle Palindrome string with case sensitivity and unicode
+8.1k Golang : How to control fmt or log print format?
+23.2k Golang : convert rune to integer value
+12.2k Golang : Strings comparison