How to read or write file from stream in Golang?

PHPz
Release: 2024-06-04 09:37:58
Original
421 people have browsed it

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.

如何在 Golang 中从流中读取或写入文件?

How to read or write a file from a stream in Golang?

In Golang, you can use theiopackage to read from a stream or write to a file. This package provides a set of functions and interfaces for manipulating input/output streams.

Reading a file from a stream

To read a file from a stream, you can create a buffered reader using thebufio.NewReaderfunction and then use ## Read the file using methods such as #ReadStringorReadBytes.

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 } // 处理每行 } }
Copy after login

Write a file to a stream

To write a file to a stream, you can use the

io.WriteStringorio.WriteBytesfunction .

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 } }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!