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
+5.7k Golang : Grab news article text and use NLP to get each paragraph's sentences
+21.3k SSL : How to check if current certificate is sha1 or sha2
+5.3k Golang : Shortening import identifier
+34.1k Golang : Smarter Error Handling with strings.Contains()
+20.8k Golang : Get password from console input without echo or masked
+11.2k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+24.1k Golang : GORM read from database example
+26.8k Golang : Find files by name - cross platform example
+19.4k Golang : Archive directory with tar and gzip
+20.1k Nginx + FastCGI + Go Setup.
+17.3k Golang : Upload/Receive file progress indicator
+11.9k Golang : List running EC2 instances and descriptions