How to Read a Whole File into a String Variable in Go

Created
Modified

Using ioutil.ReadFile Function

ReadFile reads the file named by filename and returns the contents. A successful call returns err == nil, not err == EOF. Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported.

As of Go 1.16, this function simply calls os.ReadFile.

For example,

package main

import (
  "fmt"
  "io/ioutil"
)

func main() {
  b, err := ioutil.ReadFile("file.txt")
  if err != nil {
    // panic()
  }

  s := string(b)
  fmt.Println(s)
}
One
Two

Using bytes.ReadFrom Function

ReadFrom reads data from r until EOF and appends it to the buffer, growing the buffer as needed.

See the following example:

package main

import (
  "bytes"
  "fmt"
  "os"
)

func main() {
  buf := bytes.NewBuffer(nil)

  f, err := os.Open("file.txt")
  if err != nil {
    // panic()
  }
  defer f.Close()

  // reads data
  buf.ReadFrom(f)
  s := buf.String()
  fmt.Println(s)
}
One
Two

The return value n is the number of bytes read. Any error except io.EOF encountered during the read is also returned. If the buffer becomes too large, ReadFrom will panic with ErrTooLarge.

Using strings.Builder Function

A Builder is used to efficiently build a string using Write methods. It minimizes memory copying. The zero value is ready to use. Do not copy a non-zero Builder.

package main

import (
  "fmt"
  "io"
  "os"
  "strings"
)

func main() {

  f, err := os.Open("file.txt")
  if err != nil {
    // panic()
  }
  defer f.Close()

  // reads data
  b := new(strings.Builder)
  io.Copy(b, f)
  s := b.String()
  fmt.Println(s)
}
One
Two

Related Tags

#read# #file# #string#