加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

如何使用golang从/到文件读/写?

发布时间:2020-12-16 18:17:05 所属栏目:大数据 来源:网络整理
导读:我一直试图学习Go我自己,但我一直在努力尝试从普通文件读取和写入。 我可以得到远在文件,_:= os.Open(INFILE,0,0);但实际上获取文件的内容没有意义,因为读取函数以一个[]字节作为参数。 func (file *File) Read(b []byte) (n int,err Error) 让我们在Go
我一直试图学习Go我自己,但我一直在努力尝试从普通文件读取和写入。

我可以得到远在文件,_:= os.Open(INFILE,0,0);但实际上获取文件的内容没有意义,因为读取函数以一个[]字节作为参数。

func (file *File) Read(b []byte) (n int,err Error)
让我们在Go中创建一个Go 1兼容的读取和写入文件的方式列表。

因为文件API最近更改,大多数其他答案不能使用Go 1.他们也错过bufio这是重要的IMHO。

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

从基础开始

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.Open和os.Create,它们是os.OpenFile周围方便的包装器。我们通常不需要直接调用OpenFile。

通知处理EOF。读取尝试在每次调用时填充buf,如果到达文件结尾,则返回io.EOF作为错误。在这种情况下,buf仍然保存数据。随后对读取的读取返回零,因为读取的字节数与io.EOF相同,为错误。任何其他错误都会导致崩溃。

使用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,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非常有用,通过为我们提供轻松灵活的阅读和写入a nice API,同时在后台处理缓冲。

使用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)
    }
}

易如反掌!但使用它,只有当你确信你不是处理大文件。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读