You can use the Flush()
method provided by the bufio.Writer
type in Go to flush the buffered data to the underlying writer.
Here's an example:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
file, err := os.Create("output.txt")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
writer := bufio.NewWriter(file)
writer.WriteString("Hello, World!")
writer.Flush() // Flushes the buffered data to the file
fmt.Println("Data flushed successfully")
}
In this example, we create a new file called "output.txt" and create a bufio.Writer
to write data to the file. After writing the data using WriteString()
, we call Flush()
to flush the data to the underlying writer (in this case, the file). Finally, we print a success message indicating that the data has been flushed successfully.
Note that calling Flush()
is not always necessary, as the bufio.Writer
implements a buffer that automatically flushes data when necessary (e.g., when the buffer is full). However, in certain cases, you may want to manually flush the data to ensure it is written immediately.