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.7k Golang : Calculate Relative Strength Index(RSI) example
+7k Golang : Auto-generate reply email with text/template package
+28.1k Golang : Get and Set User-Agent examples
+6.1k Golang : Check if one string(rune) is permutation of another string(rune)
+32.6k Golang : convert(cast) bytes to string
+20.7k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."
+10.5k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter
+13.4k Golang : Rename directory
+11.5k Golang : Convert int(year) to time.Time type
+7.8k Golang : How to use Gorilla webtoolkit context package properly
+19.1k Golang : Pipe output from one os.Exec(shell command) to another command
+33.6k Golang : Save image to PNG, JPEG or GIF format.