Home  >  Article  >  Backend Development  >  How to read or write file from stream in Golang?

How to read or write file from stream in Golang?

PHPz
PHPzOriginal
2024-06-04 09:37:58481browse

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 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.

Reading a file from a stream

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 stream

To 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!

Statement:
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