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
+10.4k Golang : Random Rune generator
+21.4k Golang : Get password from console input without echo or masked
+5.2k Golang : Display packages names during compilation
+16.2k Golang : How to login and logout with JWT example
+5.1k Google : Block or disable caching of your website content
+11.1k Android Studio : Checkbox for user to select options example
+14k Golang : unknown escape sequence error
+15.5k Golang : Accurate and reliable decimal calculations
+12.8k Golang : Exit, terminating or aborting a program
+13.5k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+13.9k Golang : Activate web camera and broadcast out base64 encoded images
+6.5k Golang : Detect face in uploaded photo like GPlus