How to read and write data using the bufio package for buffered I/O in Go?

To read and write data using the bufio package for buffered I/O in Go, follow these steps:

  1. Import the bufio package:
import ( "bufio" "os" )
  1. Create a bufio.Reader to read data from an input source (e.g., file, stdin, network connection). Use the NewReader function and pass the input source as an argument:
reader := bufio.NewReader(os.Stdin) // Reads from the standard input (stdin)
  1. Read data from the input source using the ReadString or ReadBytes method of the bufio.Reader object:
  • ReadString reads until the first occurrence of the delimiter character (returns the read string including the delimiter).
  • ReadBytes reads until the first occurrence of any delimiter character (returns the read bytes including the delimiter).
inputString, _ := reader.ReadString('\n') // Reads the input until a new line character is encountered
  1. Create a bufio.Writer to write data to an output destination (e.g., file, stdout, network connection). Use the NewWriter function and pass the output destination as an argument:
writer := bufio.NewWriter(os.Stdout) // Writes to the standard output (stdout)
  1. Write data to the output destination using the WriteString or Write method of the bufio.Writer object:
  • WriteString writes a string.
  • Write writes a byte slice.
outputString := "Hello, World!" writer.WriteString(outputString)
  1. Flush the buffered data to ensure it is written to the output destination. Use the Flush method of the bufio.Writer object:
writer.Flush()
  1. Close the input and output sources if necessary:
os.Stdin.Close() os.Stdout.Close()

That's it! You have now learned how to read and write data using the bufio package in Go.