博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
golang文件读写三种方式——bufio,ioutil和os.create
阅读量:6029 次
发布时间:2019-06-20

本文共 2635 字,大约阅读时间需要 8 分钟。

package mainimport (    "bufio"    "fmt"    "io/ioutil"    "os")func check(e error) {    if e != nil {        panic(e)    }}func main() {    d1 := []byte("hello\ngo\n")    err := ioutil.WriteFile("/tmp/dat1", d1, 0644)    check(err)    f, err := os.Create("/tmp/dat2")    check(err)    defer f.Close()    d2 := []byte{115, 111, 109, 101, 10}    n2, err := f.Write(d2)    check(err)    fmt.Printf("wrote %d bytes\n", n2)    n3, err := f.WriteString("writes\n")    fmt.Printf("wrote %d bytes\n", n3)    f.Sync()    w := bufio.NewWriter(f)    n4, err := w.WriteString("buffered\n")    fmt.Printf("wrote %d bytes\n", n4)    w.Flush()}

 

下面内容摘自:https://stackoverflow.com/questions/1821811/how-to-read-write-from-to-file-using-golang

Start with the basics

package mainimport ( "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 mainimport ( "bufio" "io" "os" ) 见链接

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  for reading and writing easily and flexibly, while it handles buffering behind the scenes.

Using ioutil

package mainimport ( "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.

本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/bonelee/p/6893398.html,如需转载请自行联系原作者

你可能感兴趣的文章
Google Chrome开发者工具
查看>>
第一阶段冲刺报告(一)
查看>>
使用crontab调度任务
查看>>
ctr预估论文梳理和个人理解
查看>>
【转载】SQL经验小记
查看>>
zookeeper集群搭建 docker+zk集群搭建
查看>>
Vue2.5笔记:Vue的实例与生命周期
查看>>
论JVM爆炸的几种姿势及自救方法
查看>>
联合体、结构体简析
查看>>
使用throw让服务器端与客户端进行数据交互[Java]
查看>>
java反射与代理
查看>>
深度分析Java的ClassLoader机制(源码级别)
查看>>
微服务架构选Java还是选Go - 多用户负载测试
查看>>
我的友情链接
查看>>
Javascript中的异步如何实现回调
查看>>
halcon算子介绍
查看>>
挖掘你不知道的windowsxp中的带宽潜能
查看>>
Software Engineering 招聘要求
查看>>
【转载】InstallAnyWhere自动化制作安装包的知识
查看>>
69、iSCSI共享存储配置实战
查看>>