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.

golang文件读写三种方式——bufio,ioutil和os.create的更多相关文章

  1. 前端js,css文件合并三种方式,bat命令

    前端js,css文件合并三种方式,bat命令 前端js文件该如何合并三个方式如下:1. 一个大文件,所有js合并成一个大文件,所有页面都引用它.2. 各个页面大文件,各自页面合并生成自己所需js的大文 ...

  2. android中解析文件的三种方式

    android中解析文件的三种方式     好久没有动手写点东西了,最近在研究android的相关技术,现在就android中解析文件的三种方式做以下总结.其主要有:SAX(Simple API fo ...

  3. 转 Velocity中加载vm文件的三种方式

    Velocity中加载vm文件的三种方式   velocitypropertiespath Velocity中加载vm文件的三种方式:    方式一:加载classpath目录下的vm文件 Prope ...

  4. Velocity中加载vm文件的三种方式

    Velocity中加载vm文件的三种方式: a.  加载classpath目录下的vm文件 /** * 初始化Velocity引擎 * --VelocityEngine是单例模式,线程安全 * @th ...

  5. 解析Xml文件的三种方式及其特点

    解析Xml文件的三种方式 1.Sax解析(simple api  for xml) 使用流式处理的方式,它并不记录所读内容的相关信息.它是一种以事件为驱动的XML API,解析速度快,占用内存少.使用 ...

  6. 【spring Boot】spring boot获取资源文件的三种方式【两种情况下】

    首先声明一点,springboot获取资源文件,需要看是 1>从spring boot默认的application.properties资源文件中获取 2>还是从自定义的资源文件中获取 带 ...

  7. Ajax上传数据和上传文件(三种方式)

    Ajax向后端发送数据可以有三种方式:原生Ajax方式,jQuery Ajax方式,iframe+form 方式(伪造Ajax方式) <!DOCTYPE html> <html la ...

  8. delphi之读写文件的三种方式

    一.Tstrings.Tstringlist procedure TForm1.Button2Click(Sender: TObject); var strlist: TStringList; pat ...

  9. 前端js文件合并三种方式

    最近在思考前端js文件该如何合并,当然不包括不能合并文件,而是我们能合并的文件,想了想应该也只有三种方式. 三个方式如下: 1. 一个大文件,所有js合并成一个大文件,所有页面都引用它. 2. 各个页 ...

随机推荐

  1. CSS——宠物demo

    注意:ul中自带padding值,需要清除. <!DOCTYPE html> <html lang="en"> <head> <meta ...

  2. Caffe2:段错误(核心 已转储)

    测试Caffe的时候, cd ~ && python -c 'from caffe2.python import core' 2>/dev/null && ech ...

  3. 如何知道自己的CPU支持SLAT

    因为WP8 SDK发布,很多WP8的开发者们也开始陆续安装WP8的SDK的,然而安装WP8的SDK有很多软件和硬件的要求,其中有一个就是——要求CPU支持二级地址转换(SLAT),如果CPU不支持二级 ...

  4. id 转 entity

    object 是 entity原始的类 要使用id转化成entity要先将id.getobject 然后将这个值 (entity)转化成entity entity ent =id.getentity& ...

  5. CentOS下使用yum安装配置和使用svn

    安装说明 系统环境:CentOS-6.3安装方式:yum install (源码安装容易产生版本兼容的问题)安装软件:系统自动下载SVN软件 检查已安装版本 ? 1 2 3 4 5 6 7 8 9 1 ...

  6. CAD绘一个文字自动剧中的标注 (com接口)

    主要用到函数说明: _DMxDrawX::DrawDimRotated 绘制一个线型标注.详细说明如下: 参数 说明 DOUBLE dExtLine1PointX 输入第一条界线的起始点X值 DOUB ...

  7. B+树知识点

    B+树介绍   目录 B+树 B+树的插入操作 B+树的删除操作 回到顶部 B+树 B+树和二叉树.平衡二叉树一样,都是经典的数据结构.B+树由B树和索引顺序访问方法(ISAM,是不是很熟悉?对,这也 ...

  8. vue-router的基本使用和配置

    1.在main.js文件中引入相关模块以及组件及实例化vue对象配置选项路由及渲染App组件 默认设置如下: import Vue from 'vue' import App from './App' ...

  9. [C++] 配平化学方程式算法的封装

    有人已经实现了配平的方法,在此不再重复介绍. https://www.cnblogs.com/Elfish/p/7631603.html 但是,上述的方法所提供的代码还是存在着问题,需要进一步修改. ...

  10. JAVA经典题--计算一个字符串中每个字符出现的次数

    需求:  计算一个字符串中每个字符出现的次数 思路: 通过toCharArray()拿到一个字符数组--> 遍历数组,将数组元素作为key,数值1作为value存入map容器--> 如果k ...