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.4k Golang : Simple File Server
+9.6k Golang : Replace a parameter's value inside a configuration file example
+5.6k Golang : Humanize and Titleize functions
+17.2k Golang : Read binary file into memory
+4.7k Golang : Grab news article text and use NLP to get each paragraph's sentences
+26k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+24.8k Golang : Convert(cast) string to uint8 type and back to string
+22.8k Golang : Daemonizing a simple web server process example
+9.4k Golang : Select region of interest with mouse click and crop from image
+17.7k Golang : Delete duplicate items from a slice/array
+8.4k Golang : How to protect your source code from client, hosting company or hacker?
+13.7k nginx: [emerg] unknown directive "ssl"