How to read and write text data with character encoding (e.g., UTF-8) in Go?

In Go, you can read and write text data with character encoding using the "io" and "bufio" packages. Here's an example:

Reading Text Data with Character Encoding:

package main import ( "bufio" "fmt" "io" "os" ) func main() { // Open the file for reading file, err := os.Open("input.txt") if err != nil { fmt.Println("Error opening file:", err) return } defer file.Close() // Create a reader with the correct character encoding reader := bufio.NewReader(file) // Read the file line by line for { line, err := reader.ReadString('\n') if err != nil && err != io.EOF { fmt.Println("Error reading line:", err) break } // Process the line // ... if err == io.EOF { break } } }

Writing Text Data with Character Encoding:

package main import ( "bufio" "fmt" "os" ) func main() { // Open the file for writing file, err := os.Create("output.txt") if err != nil { fmt.Println("Error opening file:", err) return } defer file.Close() // Create a writer with the correct character encoding writer := bufio.NewWriter(file) // Write text data to the file text := "Hello, 世界" _, err = writer.WriteString(text) if err != nil { fmt.Println("Error writing text:", err) } // Flush the writer to ensure all data is written to the file err = writer.Flush() if err != nil { fmt.Println("Error flushing writer:", err) } }

Make sure to replace "input.txt" and "output.txt" with the actual input and output file paths. Also, you may need to handle specific errors and perform appropriate error checks as per your requirements.