Golang program to convert file to byte array


In Go programming language we can use byte function and ioutil.ReadFile function to convert a file into byte array. The os package file type that offers ways to open, read from, write to, and manipulate files whereas array is a fixed-size group of identical elements that may be accessed by their respective indexes, which are integers with a zero-based basis. An array's size is predetermined at the moment of declaration and cannot be altered later on. When storing a set of data with a known number of elements, arrays in Go are handy, but they have some drawbacks, such as the requirement for more memory when resizing the array

Method 1: Using byte function

This method opens a file with the os package, reads data from the file with the bufio package, then prints the byte array with the fmt package. The OS is used to open the file at first. Utilizes the file after the open function. Retrieve the file's size using the stat method. After that, it uses the file and makes a byte slice the same size as the file. The file's content is read into the byte slice using the read technique. The byte slice is printed out last.

Syntax

Bufio.newReader

This function belongs to Go's bufio package. The primary goal of this function is to read the data in larger chunks instead of line by line and store in buffer. The io.reader and buffer size are passed as arguements in this function.

Algorithm

  • Step 1 − Create a package main and declare fmt(format package), bufio, io and os package in the program where main produces executable codes and fmt helps in formatting input and output.

  • Step 2 − Utilize the os.Open function to open the file and deal with any potential errors.

  • Step 3 − In the next step use the Stat method to retrieve the file's metadata, then save it to a variable.

  • Step 4 − Make a byte slice the size of the file as determined by the metadata.

  • Step 5 − Then, to read the file into the byte slice, use a bufio reader.

  • Step 6 − While reading the file into the byte slice, look for any mistakes and deal with them.

  • Step 7 − The file's contents are now present in the byte slice, which can be used as needed.

  • Step 8 − Ioutil can also be used to complete Steps 3 through 6.

  • Step 9 − When using the ReadFile method, the entire file is read into a byte slice, which is then returned together with any errors that may have occurred.

Example

In this example, we will use byte function to convert file to byte array.

package main
import (
   "bufio"
   "fmt"
   "io"
   "os"
)

func main() {
   file, err := os.Open("filename.txt")
   if err != nil {
		fmt.Println(err)
      return
	}
   defer file.Close()

   // Get the file size
   stat, err := file.Stat()
   if err != nil {
      fmt.Println(err)
      return
   }

   // Read the file into a byte slice
   bs := make([]byte, stat.Size())
   _, err = bufio.NewReader(file).Read(bs)
   if err != nil && err != io.EOF {
      fmt.Println(err)
      return
   }
   fmt.Println(bs)
}

Output

[72 101 108 108 111 32 87 111 114 108 100 33]

Method 2: Using ioutil.ReadFile function

In this following method, the complete contents of the file are read into a byte slice using the ioutil package. The ioutil.ReadFile function returns a byte slice after reading the full file's contents into memory. The application will output an error message if there is a problem reading the file. The file's content, which is displayed as a byte array in the form of the byte slice, is then printed by the application. Let’s have a look at the code and the algorithm to see how this method is executed.

Syntax

Ioutil.ReadFile

This function is available in the ioutil package and is used to read the contents of a file with filename as an input in the function.

Algorithm

  • Step 1 − Create a package main and declare fmt(format package, io/ioutil package in the program where main produces executable codes and fmt helps in formatting input and output.

  • Step 2 − Use the ioutil. ReadFile function to read the full file's content into a single byte slice.

  • Step 3 − Check for any mistakes while reading files.

  • Step 4 − Print the file's content, which is represented as a byte array in the byte slice.

  • Step 5 − Due to the use of the ioutil, this program is shorter and simpler than the previous one.

  • Step 6 − Use the ReadFile function to quickly read a file's whole contents into memory.

Example

In this example we will ioutil.ReadFile function to convert file to byte array. Let’s have a look at the code.

package main
import (
	"fmt"
	"io/ioutil"
)

func main() {
	v, err := ioutil.ReadFile("myfile.txt")  //read the content of file
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(v) //print the file content
}

Output

[72 101 108 108 111 32 87 111 114 108 100 33]

Conclusion

We executed the program of converting the file to byte array using two examples. In the first example we used byte function and in the second example we used the ioutil.ReadFile function to execute the program.

Updated on: 21-Feb-2023

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements