如何使用 Go 从/向文件读/写 [英] How to read/write from/to a file using Go

查看:25
本文介绍了如何使用 Go 从/向文件读/写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试自己学习 Go,但我一直在尝试读取和写入普通文件.

I've been trying to learn Go on my own, but I've been stumped on trying read from and write to ordinary files.

我可以得到inFile, _ := os.Open(INFILE, 0, 0),但实际上获取文件的内容没有意义,因为read函数以 []byte 作为参数.

I can get as far as inFile, _ := os.Open(INFILE, 0, 0), but actually getting the content of the file doesn't make sense, because the read function takes a []byte as a parameter.

func (file *File) Read(b []byte) (n int, err Error)

推荐答案

让我们制作一个 Go 1 兼容的列表,列出在 Go 中读写文件的所有方式.

Let's make a Go 1-compatible list of all the ways to read and write files in Go.

因为文件 API 最近发生了变化,并且大多数其他答案不适用于 Go 1.他们也错过了 bufio,恕我直言很重要.

Because file API has changed recently and most other answers don't work with Go 1. They also miss bufio which is important IMHO.

在以下示例中,我通过读取文件并写入目标文件来复制文件.

In the following examples I copy a file by reading from it and writing to the destination file.

从基础开始

package main

import (
    "io"
    "os"
)

func main() {
    // open input file
    fi, err := os.Open("input.txt")
    if err != nil {
        panic(err)
    }
    // close fi on exit and check for its returned error
    defer func() {
        if err := fi.Close(); err != nil {
            panic(err)
        }
    }()

    // open output file
    fo, err := os.Create("output.txt")
    if err != nil {
        panic(err)
    }
    // close fo on exit and check for its returned error
    defer func() {
        if err := fo.Close(); err != nil {
            panic(err)
        }
    }()

    // make a buffer to keep chunks that are read
    buf := make([]byte, 1024)
    for {
        // read a chunk
        n, err := fi.Read(buf)
        if err != nil && err != io.EOF {
            panic(err)
        }
        if n == 0 {
            break
        }

        // write a chunk
        if _, err := fo.Write(buf[:n]); err != nil {
            panic(err)
        }
    }
}

这里我使用了 os.Openos.Create,它们是 os.OpenFile 的方便包装器.我们通常不需要直接调用OpenFile.

Here I used os.Open and os.Create which are convenient wrappers around os.OpenFile. We usually don't need to call OpenFile directly.

注意处理 EOF.Read 尝试在每次调用时填充 buf,并在到达文件末尾时返回 io.EOF 作为错误.在这种情况下,buf 仍将保存数据.随后对 Read 的调用返回零作为读取的字节数和相同的 io.EOF 作为错误.任何其他错误都会导致恐慌.

Notice treating EOF. Read tries to fill buf on each call, and returns io.EOF as error if it reaches end of file in doing so. In this case buf will still hold data. Consequent calls to Read returns zero as the number of bytes read and same io.EOF as error. Any other error will lead to a panic.

使用bufio

package main

import (
    "bufio"
    "io"
    "os"
)

func main() {
    // open input file
    fi, err := os.Open("input.txt")
    if err != nil {
        panic(err)
    }
    // close fi on exit and check for its returned error
    defer func() {
        if err := fi.Close(); err != nil {
            panic(err)
        }
    }()
    // make a read buffer
    r := bufio.NewReader(fi)

    // open output file
    fo, err := os.Create("output.txt")
    if err != nil {
        panic(err)
    }
    // close fo on exit and check for its returned error
    defer func() {
        if err := fo.Close(); err != nil {
            panic(err)
        }
    }()
    // make a write buffer
    w := bufio.NewWriter(fo)

    // make a buffer to keep chunks that are read
    buf := make([]byte, 1024)
    for {
        // read a chunk
        n, err := r.Read(buf)
        if err != nil && err != io.EOF {
            panic(err)
        }
        if n == 0 {
            break
        }

        // write a chunk
        if _, err := w.Write(buf[:n]); err != nil {
            panic(err)
        }
    }

    if err = w.Flush(); err != nil {
        panic(err)
    }
}

bufio 在这里只是充当缓冲区,因为我们与数据没有太多关系.在大多数其他情况下(特别是文本文件)bufio 非常有用,它为我们提供了 一个很好的 API,用于轻松灵活地读写,同时在后台处理缓冲.

bufio is just acting as a buffer here, because we don't have much to do with data. In most other situations (specially with text files) bufio is very useful by giving us a nice API for reading and writing easily and flexibly, while it handles buffering behind the scenes.

注意:以下代码适用于较旧的 Go 版本(Go 1.15 及更早版本).事情变了.对于新方法,请查看此答案.

Note: The following code is for older Go versions (Go 1.15 and before). Things have changed. For the new way, take a look at this answer.

使用ioutil

package main

import (
    "io/ioutil"
)

func main() {
    // read the whole file at once
    b, err := ioutil.ReadFile("input.txt")
    if err != nil {
        panic(err)
    }

    // write the whole body at once
    err = ioutil.WriteFile("output.txt", b, 0644)
    if err != nil {
        panic(err)
    }
}

像馅饼一样简单!但只有在您确定不处理大文件时才使用它.

Easy as pie! But use it only if you're sure you're not dealing with big files.

这篇关于如何使用 Go 从/向文件读/写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆