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
+20k Golang : Compare floating-point numbers
+7.1k Golang : Null and nil value
+11.9k Golang : Find and draw contours with OpenCV example
+22.8k Golang : Calculate time different
+5.3k Javascript : How to loop over and parse JSON data?
+8.9k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+10.4k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+7.1k Golang : How to fix html/template : "somefile" is undefined error?
+24.4k Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
+12.7k Golang : Convert int(year) to time.Time type
+5.3k Golang : Intercept, inject and replay HTTP traffics from web server
+29.2k Golang : JQuery AJAX post data to server and send data back to client example