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
+3.8k Golang : Return multiple values from function
+12.2k Golang : Find commonalities in two slices or arrays example
+14.1k Golang : Clone with pointer and modify value
+39k Golang : How to check if a string contains another sub-string?
+7.1k Golang : Take screen shot of browser with JQuery example
+9.8k SSL : The certificate is not trusted because no issuer chain was provided
+17.7k Golang : Append content to a file
+45.8k Golang : Upload file from web browser to server
+7.8k Golang : Load ASN1 encoded DSA public key PEM file example
+16.1k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+3.5k Golang : Convert lines of string into list for delete and insert operation
+19.8k Golang : Fix type interface{} has no field or no methods and type assertions example