To read and write data using the bufio package for buffered I/O in Go, follow these steps:
- Import the bufio package:
import (
"bufio"
"os"
)
- 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)
- 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
- 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)
- 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)
- Flush the buffered data to ensure it is written to the output destination. Use the Flush method of the bufio.Writer object:
writer.Flush()
- 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.