golang文件读写三种方式——bufio,ioutil和os.create

简介:
复制代码
package main
import (
    "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 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" ) 见链接

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.














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

相关文章
|
Ubuntu Linux Go
golang编译成Linux可运行文件
本文介绍了如何在 Linux 上编译和运行 Golang 程序,涵盖了本地编译和交叉编译的步骤。通过这些步骤,您可以轻松地将 Golang 程序编译成适合 Linux 平台的可执行文件,并在目标服务器上运行。掌握这些技巧,可以提高开发和部署 Golang 应用的效率。
2754 14
|
Python
文件元数据获取方法对比:`os.path` 与 `os.stat`
本文对比了Python中两种获取文件元数据的方法:`os.path`和`os.stat`。通过示例代码展示了如何获取文件大小和修改时间,并从性能、功能性和代码可读性三方面进行了详细对比。最终给出了根据具体需求选择合适方法的最佳实践建议。
316 2
|
Unix Linux Go
go进阶编程:Golang中的文件与文件夹操作指南
本文详细介绍了Golang中文件与文件夹的基本操作,包括读取、写入、创建、删除和遍历等。通过示例代码展示了如何使用`os`和`io/ioutil`包进行文件操作,并强调了错误处理、权限控制和路径问题的重要性。适合初学者和有经验的开发者参考。
301 4
|
存储 Java iOS开发
MacOS环境-手写操作系统-43-dir命令的实现 和 文件写入
MacOS环境-手写操作系统-43-dir命令的实现 和 文件写入
212 0
|
JSON 监控 应用服务中间件
[golang]使用tail追踪文件变更
[golang]使用tail追踪文件变更
207 0
|
缓存 移动开发 Go
golang bufio解析
golang bufio解析
226 0
|
Java 开发工具 Android开发
详细解读Android开发DNK开发将.c文件打包成os
详细解读Android开发DNK开发将.c文件打包成os
235 0
|
移动开发 Go
golang bufio包怎么用?
`bufio` 是 Go 语言中用于提高 I/O 性能的包,它通过使用缓冲区减少对低效磁盘 I/O 操作的调用。简而言之,`bufio` 提供带缓冲的读写功能,减少读取或写入文件时的系统调用次数,从而提升程序性能。
203 0
|
消息中间件 Java Kafka
实时计算 Flink版操作报错合集之RocksDB在尝试打开更多文件时达到了操作系统允许的最大打开文件数限制,该怎么办
在使用实时计算Flink版过程中,可能会遇到各种错误,了解这些错误的原因及解决方法对于高效排错至关重要。针对具体问题,查看Flink的日志是关键,它们通常会提供更详细的错误信息和堆栈跟踪,有助于定位问题。此外,Flink社区文档和官方论坛也是寻求帮助的好去处。以下是一些常见的操作报错及其可能的原因与解决策略。
351 0
|
缓存 Linux Windows
初识Linux操作系统(根目录下的重要文件)(命令提示符的含义)
Linux系统基于"一切皆文件"的理念,重要文件分布在如/root(root用户目录)、/home(普通用户目录)、/etc(应用配置)、/dev(设备文件)、/boot(内核及启动文件)、/proc(动态系统信息)、/lib64(库文件)、/opt(软件存放)、/tmp(临时文件)。"[root@localhost ~]#"代表管理员在root目录,"$"代表普通用户。创建新用户用`useradd`命令。调节终端字体大小:Ctrl+Shift++增大,Ctrl+减号缩小。绝对路径从根目录开始,相对路径从当前目录开始。

推荐镜像

更多
下一篇
开通oss服务