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

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

问题描述

我一直在努力学习Go,但是我一直在努力尝试读取和写入普通文件。



我可以得到尽管 inFile,_:= os.Open(INFILE,0,0),但实际获取文件的内容没有意义,因为read函数需要 [] byte 作为参数。 )读取(b []字节)(n int,err Error)


解决方案



由于文件API最近发生了变化,而其他大多数答案都没有显示出来,所以我们在Go上创建了一个Go 1兼容的列表,用于读取和写入文件。 '不适用于Go 1.他们也错过了 bufio 这是很重要的恕我直言。



在下面的例子中,我复制通过阅读文件并写入目标文件。



从基础开始

 包主

导入(
io
os


func main(){
//打开输入文件
fi,err:= os.Open(input.txt)
if err!= nil {
panic(err)
}
//关闭出口并检查返回的错误
推迟func(){
if err:= fi.Close (); err!= nil {
panic(err)
}
}()

//打开输出文件
fo,err:= os.Create (output.txt)
if err!= nil {
panic(err)
}
//退出时关闭fo并检查它返回的错误
推迟func(){
if err:= fo.Close(); err!= nil {
panic(err)
}
}()

//创建一个缓冲区来保存读取的块
buf: = make([] byte,1024)
for {
//读取一个块
n,err:= fi.Read(buf)
if err!= nil&& amp ; err!= io.EOF {
panic(err)
}
if n == 0 {
break
}

//写一个块
if _,err:= fo.Write(buf [:n]); err!= nil {
panic(err)
}
}
}

这里我使用了 os.Open os.Create C $ C> os.OpenFile 。我们通常不需要直接调用 OpenFile



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



使用 bufio

 包裹主要

进口(
bufio
io
os


func main(){
//打开输入文件
fi,err:= os.Open(input.txt)
if err!= nil {
panic(err)
}
//关闭出口并检查返回的错误
推迟func(){
if err:= fi.Close(); err!= nil {
panic(err)
}
}()
//创建一个读缓冲区
r:= bufio.NewReader(fi)

//打开输出文件
fo,err:= os.Create(output.txt)
if err!= nil {
panic(err)

//在出口处关闭并检查其返回的错误
推迟func(){
if err:= fo.Close(); err!= nil {
panic(err)
}
}()
//写一个写缓冲区
w:= bufio.NewWriter(fo)

//创建一个缓冲区以保持读取的块
buf:= make([] byte,1024)
for {
//读取块
n ,err:= r.Read(buf)
if err!= nil&& err!= io.EOF {
panic(err)
}
if n == 0 {
break
}

//写一个块
if _,err:= w.Write(buf [:n]); err!= nil {
panic(err)
}
}

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

bufio 在这里只是充当缓冲区,因为我们没有太多关于数据的事情。在大多数其他情况下(特别是使用文本文件) bufio 通过给我们一个不错的API ,可以轻松灵活地进行读写操作,同时它可以在后台处理缓冲。

使用 ioutil

 包主

import(
io / ioutil


func main(){
//一次读取整个文件
b,err:= ioutil .ReadFile(input.txt)
if err!= nil {
panic(err)
}

//立刻写全身
err = ioutil.WriteFile(output.txt,b,0644)
if err!= nil {
panic(err)
}
}

轻松如馅饼!但是,只有在确定你没有处理大文件时才使用它。


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

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)

解决方案

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

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.

Start with the basics

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

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

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.

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

Using 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天全站免登陆