In Go programming, the bufio package provides functions to read from and write to I/O buffers. The Writer type is a part of this package that helps in writing data to an I/O writer like a file or standard output.
import (
"bufio"
"os"
"fmt"
)To create a Writer, we use the NewWriter function from the bufio package. Let's write data to a file:
f, _ := os.Create("example.txt")
writer := bufio.NewWriter(f)
writer.WriteString("Hello, World!")
writer.Flush()
f.Close()In the above example, we create a new file named example.txt and a Writer object using the file. The WriteString method is used to write the string to the Writer, and Flush ensures that all buffered data is written immediately.
To write data to the standard output, we can use os.Stdout instead of creating a new file:
writer := bufio.NewWriter(os.Stdout)
writer.WriteString("Welcome to bufio.Writer!\n")
writer.Flush()Although the bufio package is primarily used for writing, it also provides methods to read data from a reader, which is the counterpart of a writer. You can read data from a bufio.Writer using the bufio.Scanner type.
What is bufio.Writer used for in Go programming?
Happy Coding! 🎉🥳