Home > Article > Backend Development > How to read or write file from stream in Golang?
In Go, you can read from a stream or write a file using the io package: Reading a file from a stream: Create a buffered reader. Read the file line by line using the ReadString or ReadBytes method. Write a file to a stream: Use the WriteString or WriteBytes function to write to a file.
In Golang, you can use the io
package to read from a stream or write to a file. This package provides a set of functions and interfaces for manipulating input/output streams.
To read a file from a stream, you can create a buffered reader using the bufio.NewReader
function and then use ## Read the file using methods such as #ReadString or
ReadBytes.
package main import ( "bufio" "fmt" "os" ) func main() { // 打开文件 file, err := os.Open("file.txt") if err != nil { fmt.Println(err) return } defer file.Close() // 创建缓冲读取器 reader := bufio.NewReader(file) // 逐行读取文件 for { line, err := reader.ReadString('\n') if err == io.EOF { break } if err != nil { fmt.Println(err) return } // 处理每行 } }Write a file to a streamTo write a file to a stream, you can use the
io.WriteString or
io.WriteBytes function .
package main import ( "fmt" "os" ) func main() { // 打开文件 file, err := os.Create("file.txt") if err != nil { fmt.Println(err) return } defer file.Close() // 写入文件 _, err = file.WriteString("Hello, world!") if err != nil { fmt.Println(err) return } }
The above is the detailed content of How to read or write file from stream in Golang?. For more information, please follow other related articles on the PHP Chinese website!