How to read and write binary data with bufio in Go?

To read and write binary data with bufio in Go, you can follow these steps:

  1. Create a new bufio.Reader or bufio.Writer object. These objects are used to read from and write to an underlying io.Reader or io.Writer, respectively.

  2. Wrap the underlying io.Reader or io.Writer with the bufio.Reader or bufio.Writer object, respectively. This allows you to read and write data in a buffered manner.

  3. Use the appropriate methods provided by bufio.Reader or bufio.Writer to read and write binary data. For example, you can use the Read or ReadFull methods to read binary data from a reader, and the Write or WriteString methods to write binary data to a writer.

Here's an example that demonstrates how to read and write binary data using bufio:

package main import ( "bufio" "fmt" "os" ) func main() { file, err := os.Create("binaryData.bin") if err != nil { fmt.Println("Failed to create file:", err) return } defer file.Close() // Create a bufio.Writer to write binary data writer := bufio.NewWriter(file) // Write binary data using the Write method data := []byte{0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x47, 0x6f, 0x21} _, err = writer.Write(data) if err != nil { fmt.Println("Failed to write binary data:", err) return } // Flush the writer to ensure all buffered data is written to the file err = writer.Flush() if err != nil { fmt.Println("Failed to flush writer:", err) return } // Create a bufio.Reader to read binary data reader := bufio.NewReader(file) // Read binary data using the Read method readData := make([]byte, len(data)) _, err = reader.Read(readData) if err != nil { fmt.Println("Failed to read binary data:", err) return } // Print the read binary data fmt.Printf("Read binary data: %x\n", readData) }

In this example, a binary file named "binaryData.bin" is created and opened for writing. The binary data is written to the file using bufio.Writer. Then, a bufio.Reader is created to read the binary data from the same file. The binary data is read using the Read method, and the read data is printed to the console.