使用io/ioutil进行读写文件

ioutil包

其中提到了两个方法: 
func ReadFile

func ReadFile(filename string) ([]byte, error)

ReadFile reads the file named by filename and returns the contents. A successful call returns err == nil, not err == EOF. Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported.

func WriteFile

func WriteFile(filename string, data []byte, perm os.FileMode) error

WriteFile writes data to a file named by filename. If the file does not exist, WriteFile creates it with permissions perm; otherwise WriteFile truncates it before writing

读文件:

package main

import (
"fmt"
"io/ioutil"
) func main() {
b, err := ioutil.ReadFile("test.log")
if err != nil {
fmt.Print(err)
}
fmt.Println(b)
str := string(b)
fmt.Println(str)
}

写文件:

package main

import (
"io/ioutil"
) func check(e error) {
if e != nil {
panic(e)
}
} func main() { d1 := []byte("hello\ngo\n")
err := ioutil.WriteFile("test.txt", d1, 0644)
check(err)
}

  

使用os进行读写文件

os包

首先要注意的就是两个打开文件的方法:

func Open

func Open(name string) (*File, error)

Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError.

 读文件:

fi, err := os.Open(path)
if err != nil {
panic(err)
}
defer fi.Close()

func OpenFile 
需要提供文件路径、打开模式、文件权限

func OpenFile(name string, flag int, perm FileMode) (*File, error)

OpenFile is the generalized open call; most users will use Open or Create instead. It opens the named file with specified flag (O_RDONLY etc.) and perm, (0666 etc.) if applicable. If successful, methods on the returned File can be used for I/O. If there is an error, it will be of type *PathError.

  读文件:

package main

import (
"log"
"os"
) func main() {
f, err := os.OpenFile("notes.txt", os.O_RDWR|os.O_CREATE, 0755)
if err != nil {
log.Fatal(err)
}
if err := f.Close(); err != nil {
log.Fatal(err)
}
}

  读方法

package main

import (
"bufio"
"fmt"
"io"
"os"
) func check(e error) {
if e != nil {
panic(e)
}
} func main() { f, err := os.Open("foo.dat")
check(err) b1 := make([]byte, 5)
n1, err := f.Read(b1)
check(err)
fmt.Printf("%d bytes: %s\n", n1, string(b1)) o2, err := f.Seek(6, 0)
check(err)
b2 := make([]byte, 2)
n2, err := f.Read(b2)
check(err)
fmt.Printf("%d bytes @ %d: %s\n", n2, o2, string(b2)) o3, err := f.Seek(6, 0)
check(err)
b3 := make([]byte, 2)
n3, err := io.ReadAtLeast(f, b3, 2)
check(err)
fmt.Printf("%d bytes @ %d: %s\n", n3, o3, string(b3)) _, err = f.Seek(0, 0)
check(err) r4 := bufio.NewReader(f)
b4, err := r4.Peek(5)
check(err)
fmt.Printf("5 bytes: %s\n", string(b4)) f.Close() }

  写方法

package main

import (
"bufio"
"fmt"
"os"
) func check(e error) {
if e != nil {
panic(e)
}
} func main() { 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() }

  

 几种读取文件方法速度比较

package main

import (
    "bufio"
    "fmt"
    "io"
    "io/ioutil"
    "os"
    "time"
)

func read0(path string) string {
    f, err := ioutil.ReadFile(path)
    if err != nil {
        fmt.Printf("%s\n", err)
        panic(err)
    }
    return string(f)
}

func read1(path string) string {
    fi, err := os.Open(path)
    if err != nil {
        panic(err)
    }
    defer fi.Close()

    chunks := make([]byte, 1024, 1024)
    buf := make([]byte, 1024)
    for {
        n, err := fi.Read(buf)
        if err != nil && err != io.EOF {
            panic(err)
        }
        if 0 == n {
            break
        }
        chunks = append(chunks, buf[:n]...)
    }
    return string(chunks)
}

func read2(path string) string {
    fi, err := os.Open(path)
    if err != nil {
        panic(err)
    }
    defer fi.Close()
    r := bufio.NewReader(fi)

    chunks := make([]byte, 1024, 1024)

    buf := make([]byte, 1024)
    for {
        n, err := r.Read(buf)
        if err != nil && err != io.EOF {
            panic(err)
        }
        if 0 == n {
            break
        }
        chunks = append(chunks, buf[:n]...)
    }
    return string(chunks)
}

func read3(path string) string {
    fi, err := os.Open(path)
    if err != nil {
        panic(err)
    }
    defer fi.Close()
    fd, err := ioutil.ReadAll(fi)
    return string(fd)
}

func main() {

    file := "foo.dat"

    start := time.Now()

    read0(file)
    t0 := time.Now()
    fmt.Printf("Cost time %v\n", t0.Sub(start))

    read1(file)
    t1 := time.Now()
    fmt.Printf("Cost time %v\n", t1.Sub(t0))

    read2(file)
    t2 := time.Now()
    fmt.Printf("Cost time %v\n", t2.Sub(t1))

    read3(file)
    t3 := time.Now()
    fmt.Printf("Cost time %v\n", t3.Sub(t2))

}

  

golang学习笔记 ----读写文件的更多相关文章

  1. Linux系统学习笔记:文件I/O

    Linux支持C语言中的标准I/O函数,同时它还提供了一套SUS标准的I/O库函数.和标准I/O不同,UNIX的I/O函数是不带缓冲的,即每个读写都调用内核中的一个系统调用.本篇总结UNIX的I/O并 ...

  2. golang学习笔记19 用Golang实现以太坊代币转账

    golang学习笔记19 用Golang实现以太坊代币转账 在以太坊区块链中,我们称代币为Token,是以太坊区块链中每个人都可以任意发行的数字资产.并且它必须是遵循erc20标准的,至于erc20标 ...

  3. golang学习笔记12 beego table name `xxx` repeat register, must be unique 错误问题

    golang学习笔记12 beego table name `xxx` repeat register, must be unique 错误问题 今天测试了重新建一个项目生成新的表,然后复制到旧的项目 ...

  4. golang学习笔记8 beego参数配置 打包linux命令

    golang学习笔记8 beego参数配置 打包linux命令 参数配置 - beego: 简约 & 强大并存的 Go 应用框架https://beego.me/docs/mvc/contro ...

  5. golang学习笔记7 使用beego swagger 实现API自动化文档

    golang学习笔记7 使用beego swagger 实现API自动化文档 API 自动化文档 - beego: 简约 & 强大并存的 Go 应用框架https://beego.me/doc ...

  6. golang学习笔记6 beego项目路由设置

    golang学习笔记5 beego项目路由设置 前面我们已经创建了 beego 项目,而且我们也看到它已经运行起来了,那么是如何运行起来的呢?让我们从入口文件先分析起来吧: package main ...

  7. golang学习笔记5 用bee工具创建项目 bee工具简介

    golang学习笔记5 用bee工具创建项目 bee工具简介 Bee 工具的使用 - beego: 简约 & 强大并存的 Go 应用框架https://beego.me/docs/instal ...

  8. go语言,golang学习笔记4 用beego跑一个web应用

    go语言,golang学习笔记4 用beego跑一个web应用 首页 - beego: 简约 & 强大并存的 Go 应用框架https://beego.me/ 更新的命令是加个 -u 参数,g ...

  9. go语言,golang学习笔记2 web框架选择

    go语言,golang学习笔记2 web框架选择 用什么go web框架比较好呢?能不能推荐个中文资料多的web框架呢? beego框架用的人最多,中文资料最多 首页 - beego: 简约 & ...

随机推荐

  1. (纪录片)光的故事 BBC Light Fantastic (2004)

    简介: 导演: Jeremy Turner主演: Simon Schaffer / Dimitri Andreas ... Al Hazen / Edmund Dehn ... Priest/Old ...

  2. MySQL常用处理方法

    1.replace into replace into t(id, update_time) values(1, now());或 replace into t(id, update_time) se ...

  3. 获取屏幕的宽和高-Display中getHeight()和getWidth() 官方已废弃

    getHeight()和getWidth() deprecated in API level 13 Display dp=getWindowManager().getDefaultDisplay(); ...

  4. 微信小程序 - 下拉菜单组件

    使用: 1.导入组件 2.使用组件 3.数据传入 4. 获取数据(通过同步缓存,获取“choose”)- 发送到后端 点击下载:小程序-下拉组件.

  5. Android Things专题 1.前世今生

    文| 谷歌开发人员技术专家, 物联网方向 (IOT GDE) 王玉成(York Wang) 2016 年 12 月,Google 公布了 Developer Preview 版的 Android Th ...

  6. node.js模块化写法入门

    子模块的写法: function SVN(){ console.log('svn initialized'); return this; } function getInstance() { cons ...

  7. java第四节 异常/访问控制/jar包

    /* 异常 异常定义了程序中遇到的非致命的错误,而不是编译时的语法错误,如程序要打开一个不存在的文件 网络连接中断,操作数越界,装载一个不存在的类等 try, catch语句 throws关键字 自定 ...

  8. CentOS7 通过代理上网

    1.修改/etc/profile,增加以下内容: http_proxy=http://[代理地址]:[代理地址的端口]/ https_proxy=http://[代理地址]:[代理地址的端口]/ ex ...

  9. Eclipse和MyEclipse使用技巧--MyEclipse下创建的项目导入到Eclipse中详细的图文配置方法

    一.情景再现. 有些人比较喜欢用Myeclipse开发,有些人却比较喜欢用eclipse开发.但是其中有一个问题,Myeclipse里面的项目导入的时候出现了一个小小的问题. 如下: 二.说明问题 导 ...

  10. vsftp 虚拟用户测试

    1.创建用于进行FTP验证的帐号密码数据库文件,单数行为账户名,偶数行为密码.[root@rhel1 vsftpd]# vi /etc/vsftpd/vuser.listuser1123456user ...