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.9k Golang : How to get a user home directory path?
+5.6k Unix/Linux : How to test user agents blocked successfully ?
+9.7k Golang : Ordinal and Ordinalize a given number to the English ordinal numeral
+6.1k Golang : Selection sort example
+23.3k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+17k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+4.7k Python : Find out the variable type and determine the type with simple test
+9.8k Golang : Test a slice of integers for odd and even numbers
+9k Golang : Apply Histogram Equalization to color images
+12.9k Golang : List objects in AWS S3 bucket
+11.3k Golang : Display a text file line by line with line number example
+9.9k Golang : Compare files modify date example