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
+9.8k PHP : Get coordinates latitude/longitude from string
+5.7k Python : Print unicode escape characters and string
+15.7k Golang : Force download file example
+9.6k Golang : Apply Histogram Equalization to color images
+6k Golang : Use NLP to get sentences for each paragraph example
+12.8k Golang : Pass database connection to function called from another package and HTTP Handler
+4.9k Javascript : How to get width and height of a div?
+9.1k Golang : Capture text return from exec function example
+8k Golang : Get today's weekday name and calculate target day distance example
+28.2k Golang : Move file to another directory
+46.6k Golang : Encode image to base64 example
+29.3k Golang : missing Git command