How to perform buffered reading and writing for improved I/O efficiency in Go?

To perform buffered reading and writing for improved I/O efficiency in Go, you can use the bufio package that provides buffered I/O functionality. Here's how you can use it:

  1. Import the bufio package:
import ( "bufio" "os" )
  1. Create a buffered reader or writer:
  • To perform buffered reading, create a bufio.Reader:
file, err := os.Open("input.txt") // Open the file if err != nil { log.Fatal(err) } defer file.Close() reader := bufio.NewReader(file) // Create a buffered reader
  • To perform buffered writing, create a bufio.Writer:
file, err := os.Create("output.txt") // Create the file if err != nil { log.Fatal(err) } defer file.Close() writer := bufio.NewWriter(file) // Create a buffered writer
  1. Use the buffered reader or writer to read/write data:
  • For buffered reading, use the Read method of bufio.Reader:
data, err := reader.ReadBytes('\n') // Read a line from the file if err != nil { log.Fatal(err) }
  • For buffered writing, use the Write or WriteString method of bufio.Writer:
_, err := writer.Write([]byte("Hello, World!\n")) // Write data to the file if err != nil { log.Fatal(err) } writer.Flush() // Flush the buffer to write data to the file

Note: Flush is important to ensure all the buffered data is written.

By using buffered reading and writing, you can improve I/O efficiency by reducing the number of system calls and disk operations. The bufio package takes care of managing the buffer and improves the performance of I/O operations.