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.7k Golang : Derive cryptographic key from passwords with Argon2
+5.8k Linux : Disable and enable IPv4 forwarding
+26.1k Golang : Convert IP address string to long ( unsigned 32-bit integer )
+11.2k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+9.8k Golang : Load ASN1 encoded DSA public key PEM file example
+12.1k Golang : Decompress zlib file example
+6.9k Android Studio : Hello World example
+17.4k Golang : Check if IP address is version 4 or 6
+23.9k Golang : Fix type interface{} has no field or no methods and type assertions example
+23.5k Golang : Get ASCII code from a key press(cross-platform) example
+4.3k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+9.2k Golang : Write multiple lines or divide string into multiple lines