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:
bufio
package:import (
"bufio"
"os"
)
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
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
Read
method of bufio.Reader
:data, err := reader.ReadBytes('\n') // Read a line from the file
if err != nil {
log.Fatal(err)
}
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.