To perform buffered I/O operations with custom buffers in Go, you can use the bufio
package. Here's how you can do it:
bufio
package:import (
"bufio"
"os"
)
bufio.NewWriterSize
function and specify the size of the buffer:bufferSize := 1024 // Set your desired buffer size
file, err := os.Create("output.txt")
if err != nil {
panic(err)
}
writer := bufio.NewWriterSize(file, bufferSize)
defer writer.Flush() // Flush the buffer before closing the writer
writer.Write
or writer.WriteString
functions:data := []byte("Hello, World!")
_, err = writer.Write(data)
if err != nil {
panic(err)
}
writer.Flush
:writer.Flush()
bufio.NewReaderSize
function in a similar way:file, err := os.Open("input.txt")
if err != nil {
panic(err)
}
reader := bufio.NewReaderSize(file, bufferSize)
defer file.Close()
data := make([]byte, bufferSize)
_, err = reader.Read(data)
if err != nil {
panic(err)
}
Note that you can customize the buffer size according to your needs for optimal performance. Remember to flush the buffer before closing the writer to ensure all data is written. Similarly, ensure to close the file when done reading from it.
That's how you can perform buffered I/O operations with custom buffers using the bufio
package in Go.