Golang : Convert file content into array of bytes
It is a fairly common requirement to read a file content into array of bytes and output those arrays back to a file. In this tutorial, we will explore how to convert file content into array of bytes in Go.
See the example code below :
readfileintobytes.go
package main
import (
"fmt"
"io"
"os"
"bufio"
"bytes"
)
func main () {
file, err := os.Open("testdata.txt")
if err != nil {
panic(err.Error())
}
defer file.Close()
reader := bufio.NewReader(file)
buffer := bytes.NewBuffer(make([] byte,0))
var chunk []byte
var eol bool
var str_array []string
for {
if chunk, eol, err = reader.ReadLine(); err != nil {
break
}
buffer.Write(chunk)
if !eol {
str_array = append(str_array, buffer.String())
buffer.Reset()
}
}
if err == io.EOF {
err = nil
}
fmt.Println(str_array) // you can redirect the str_array content to a file here instead of println
}
Reference :
See also : Golang : Read binary file into memory
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
+14.4k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+9k Golang : Get escape characters \u form from unicode characters
+35.1k Golang : Convert date or time stamp from string to time.Time type
+10.8k Golang : Print UTF-8 fonts on image example
+4.9k Golang : How to search a list of records or data structures
+5k Golang : Calculate US Dollar Index (DXY)
+9.6k Golang : Fix go.exe is not compatible with the version of Windows you're running
+14.9k Golang : convert string or integer to big.Int type
+4.6k Golang : Get S3 or CloudFront object or file information
+18k Golang : Execute shell command
+4.4k Javascript : How to loop over and parse JSON data?
+3.8k Facebook : How to place save to Facebook button on your website