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
+19.3k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+7.2k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+22k Golang : Convert string slice to struct and access with reflect example
+6.4k Golang : Calculate US Dollar Index (DXY)
+8.9k Yum Error: no such table: packages
+42.1k Golang : How do I convert int to uint8?
+26.3k Golang : Convert IP address string to long ( unsigned 32-bit integer )
+9.8k Golang : How to generate Code 39 barcode?
+15.7k Golang : Validate hostname
+46.7k Golang : Marshal and unmarshal json.RawMessage struct example
+8.8k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+17.7k Golang : Upload/Receive file progress indicator