读文件:

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包的介绍: 
Go语言学习之os包中文件相关的操作(The way to go)

首先要注意的就是两个打开文件的方法: 
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"
"io/ioutil"
"os"
) func check(e error) {
if e != nil {
panic(e)
}
} func main() { f, err := os.Open("/tmp/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"
"io/ioutil"
"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 := "test.log" 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)) }

运行结果: 
Cost time 4.0105ms 
Cost time 11.5043ms 
Cost time 7.0042ms 
Cost time 2.4983ms

Cost time 4.4925ms 
Cost time 11.0053ms 
Cost time 5.0082ms 
Cost time 2.9992ms

Cost time 3.9866ms 
Cost time 15.0085ms 
Cost time 7.5054ms 
Cost time 2.5035ms

Cost time 4.9989ms 
Cost time 14.0112ms 
Cost time 7.5045ms 
Cost time 3.508ms

Cost time 3.0043ms 
Cost time 15.0265ms 
Cost time 8.9884ms 
Cost time 2.0036ms

使用io/ioutil进行读写文件的更多相关文章

  1. C#常用IO流与读写文件

    .文件系统 ()文件系统类的介绍 文件操作类大都在System.IO命名空间里.FileSystemInfo类是任何文件系统类的基类:FileInfo与File表示文件系统中的文件:Directory ...

  2. java.io几种读写文件的方式

    一.Java把这些不同来源和目标的数据都统一抽象为数据流. Java语言的输入输出功能是十分强大而灵活的. 在Java类库中,IO部分的内容是很庞大的,因为它涉及的领域很广泛:标准输入输出,文件的操作 ...

  3. C#常用IO流与读写文件 (转)

    源自https://www.cnblogs.com/liyangLife/p/4797583.html 谢谢 1.文件系统 (1)文件系统类的介绍 文件操作类大都在System.IO命名空间里.Fil ...

  4. Python中的文件IO操作(读写文件、追加文件)

    Python中文件的读写包含三个步骤:打开文件,读/写文件,关闭文件. 文件打开之后必须关闭,因为在磁盘上读写文件的功能是由操作系统提供的,文件作为对象,被打开后会占用操作系统的资源,而操作系统在同一 ...

  5. Perl IO:随机读写文件

    随机读写 如果一个文件句柄是指向一个实体文件的,那么就可以对它进行随机数据的访问(包括随机读.写),随机访问表示可以读取文件中的任何一部分数据或者向文件中的任何一个位置处写入数据.实现这种随机读写的功 ...

  6. [python 学习] IO操作之读写文件

    一.读取全部文件: # -*- coding: utf-8 -*- f = open('qq_url.txt','r'); print f.read(); f.close(); 二.读取规定长度文件 ...

  7. golang学习笔记 ----读写文件

    使用io/ioutil进行读写文件 ioutil包 其中提到了两个方法: func ReadFile func ReadFile(filename string) ([]byte, error) Re ...

  8. golang读写文件

    1. 标准输入输出 os提供了标准输入输出文件: Stdin = NewFile(uintptr(syscall.Stdin), "/dev/stdin") Stdout = Ne ...

  9. 系统学习 Java IO (十三)----字符读写 Reader/Writer 及其常用子类

    目录:系统学习 Java IO---- 目录,概览 Reader Reader 类是 Java IO API 中所有 Reader 子类的基类. Reader 类似于 InputStream ,除了它 ...

随机推荐

  1. IOS 跳转页面

    1. 跳转界面,关闭自身 LoginViewController *loginViewController = [[LoginViewController alloc]initWithNibName: ...

  2. SQL生成自动序号 带有占位符(掩码),可以调整占位长度的语句

    MSSQL 语句 --声明变量 DECLARE @i int DECLARE @xh varchar(10) DECLARE @name varchar(10) Set @i = 0 --开始循环插入 ...

  3. Qt的多线程总结以及使用(一)

    Qt提供QThread类以进行多任务的处理.Qt提供的线程可以做到单个进程做不到的事情.在这里实现最简单的一个多线程.最简单的线程的基类为QThread,然后需要重写QThread的run(),在ru ...

  4. 使用js输出1000以内的水仙花数

    什么是水仙花数 水仙花数(Narcissistic number)也被称为超完全数字不变数(pluperfect digital invariant, PPDI).自恋数.自幂数.阿姆斯壮数或阿姆斯特 ...

  5. git 分布式版本控制

    一.git版本控制 管理文件夹 安装省略 1. 进入要管理的文件夹 2. 初始化 (提名) 3. 管理 4. 生成版本 对应的命令: # 进入文件夹以后 右击选git bash here #初始化 g ...

  6. django 函数和类实现分页案例

    方法一: 模拟分页from django.shortcuts import render,HttpResponse from app01 import models def hostnames(req ...

  7. Python: NumPy, Pandas学习资料

    NumPy 学习资料 书籍 NumPy Cookbook_[Idris2012] NumPy Beginner's Guide,3rd_[Idris2015] Python数据分析基础教程:NumPy ...

  8. 【Struts2】Ognl与ValueStack

    一.OGNL 1.1 概述 1.2 OGNL 五大类功能 1.3 演示 二.ValueStack 2.1 概述 2.2 ValueStack结构 2.3 结论 2.3 一些问题 三.OGNL表达式常见 ...

  9. pymysql_mysql密码重置方法,连接局域网数据库的解决办法

    https://blog.csdn.net/qq_37176126/article/details/72824106   pymysql模块的操作 https://blog.csdn.net/skh2 ...

  10. Linux内核移植的若干问题