In Go, reading and writing text files into and out of string arrays is a common requirement. Previously, this task could be accomplished using custom functions or third-party libraries. However, with the introduction of Go1.1, the bufio.Scanner API was introduced, providing a streamlined solution for this purpose.
The bufio.Scanner can be used to efficiently read lines from a file and return them as a slice of strings. The following example demonstrates how to read a file into a string array:
import "bufio" func readLines(path string) ([]string, error) { file, err := os.Open(path) if err != nil { return nil, err } defer file.Close() var lines []string scanner := bufio.NewScanner(file) for scanner.Scan() { lines = append(lines, scanner.Text()) } return lines, scanner.Err() }
Similarly, the bufio.Writer can be used to write a slice of strings to a text file:
import "bufio" func writeLines(lines []string, path string) error { file, err := os.Create(path) if err != nil { return err } defer file.Close() w := bufio.NewWriter(file) for _, line := range lines { fmt.Fprintln(w, line) } return w.Flush() }
By leveraging the bufio package, developers can effortlessly read and write text files in a clear and efficient manner in Go.
The above is the detailed content of How Can I Efficiently Read and Write Text Files to String Arrays in Go?. For more information, please follow other related articles on the PHP Chinese website!