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
+10.1k Golang : Sort and reverse sort a slice of integers
+21.1k Golang : Underscore or snake_case to camel case example
+17.8k Golang : Parse date string and convert to dd-mm-yyyy format
+23.1k Golang : Calculate time different
+16.2k Golang : Read large file with bufio.Scanner cause token too long error
+11.8k Golang : Gorilla web tool kit secure cookie example
+8.9k Golang : Find duplicate files with filepath.Walk
+14.9k Golang : GUI with Qt and OpenCV to capture image from camera
+16.8k Golang : Generate QR codes for Google Authenticator App and fix "Cannot interpret QR code" error
+6.3k Golang : How to write backslash in string?
+6.9k Golang : Get expvar(export variables) to work with multiplexer
+5.4k Golang : Calculate half life decay example