读文件:

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. hdu 1305 还是字典树

    #include<cstdio> #include<iostream> #include<string> #include<cstdlib> #defi ...

  2. Partial的应用

    Partial是局部类型的意思.允许我们将一个类.结构或接口分成几个部分,分别实现在几个不同的.cs文件中.C#编译器在编译的时候仍会将各个部分的局部类型合并成一个完整的类 局部类型的注意点1. 局部 ...

  3. dev gridview 单元格值拖拽替换

    public class GridViewDropCell { //dvginfo根据鼠标点击的x.y坐标获取该点的相关信息 private GridHitInfo downHitInfo; priv ...

  4. .net core默认不支持gb2312

    采集数据时,乱码,之前遇到过这个情况,于是老办法: 果断使用Encoding.GetEncoding(“GB2312”),抛异常.搜了下,是因为.net core默认不支持gb2312 所以,两个办法 ...

  5. python中的not的意思

    python中的not的意思 在python中,not是逻辑判断,用于布尔值true和false,not true是false,not false是true.以下是not的一些常见用法:(1)当表达式 ...

  6. Nginx安装与配置【转】

    原文:linux之nginx 作者;海燕. 一.nginx Ngix是web服务器,跟apache一样,它可以做动态请求转发.web端负载均衡.反向代理等等: tomcat是应用服务器,当然如果非用逼 ...

  7. vue项目js实现图片放大镜功能

    效果图:   我写的是vue的组件形式,方便复用,图片的宽高,缩放的比例可以自己定义 magnifier.vue <template> <div class="magnif ...

  8. 【转】在 Delphi 中创建 Linux 守护程序(服务进程)

    转自波哥的译文,必须转过来,太有价值了!原文地址在这里.以下为原文内容: 本文译自 原文链接,语言上做了精炼和排版的变更,以便更简洁明了. Delphi 开始支持 Linux 平台为 Delphi 开 ...

  9. 网络编程基础之TCP学习(二)编程案例

    TCP网络编程流程如下: 实现功能:服务器端与客户端成功通讯后返回get! 服务器端程序 #include <netdb.h> #include <sys/socket.h> ...

  10. 生成漂亮报告的Go语言代码检查工具

    上篇文章,老司机给各位同学介绍了Go语言的静态代码测试“三板斧”以及Go语言的testing类库. “三板斧”简洁明了,但是缺点也很明显,命令行执行,命令行输出.适合研发攻城狮看,不适合交给领导过目. ...