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
+4.6k Golang : Find duplicate files with filepath.Walk
+10.7k Golang : Converting a negative number to positive number
+12.1k Golang : Archive directory with tar and gzip
+15k Golang : convert int to string
+2.5k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+5.2k Golang : Determine if time variables have same calendar day
+3.4k Golang : Validate credit card example
+14.6k Golang : How to Set or Add Header http.ResponseWriter?
+15.3k Golang : missing Mercurial command
+31.1k Golang : How to get time in milliseconds?
+4.3k Golang : Meaning of omitempty in struct's field tag
+5.1k Golang : What is the default port number for connecting to MySQL/MariaDB database ?