使用io/ioutil进行读写文件
读文件:
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进行读写文件的更多相关文章
- C#常用IO流与读写文件
.文件系统 ()文件系统类的介绍 文件操作类大都在System.IO命名空间里.FileSystemInfo类是任何文件系统类的基类:FileInfo与File表示文件系统中的文件:Directory ...
- java.io几种读写文件的方式
一.Java把这些不同来源和目标的数据都统一抽象为数据流. Java语言的输入输出功能是十分强大而灵活的. 在Java类库中,IO部分的内容是很庞大的,因为它涉及的领域很广泛:标准输入输出,文件的操作 ...
- C#常用IO流与读写文件 (转)
源自https://www.cnblogs.com/liyangLife/p/4797583.html 谢谢 1.文件系统 (1)文件系统类的介绍 文件操作类大都在System.IO命名空间里.Fil ...
- Python中的文件IO操作(读写文件、追加文件)
Python中文件的读写包含三个步骤:打开文件,读/写文件,关闭文件. 文件打开之后必须关闭,因为在磁盘上读写文件的功能是由操作系统提供的,文件作为对象,被打开后会占用操作系统的资源,而操作系统在同一 ...
- Perl IO:随机读写文件
随机读写 如果一个文件句柄是指向一个实体文件的,那么就可以对它进行随机数据的访问(包括随机读.写),随机访问表示可以读取文件中的任何一部分数据或者向文件中的任何一个位置处写入数据.实现这种随机读写的功 ...
- [python 学习] IO操作之读写文件
一.读取全部文件: # -*- coding: utf-8 -*- f = open('qq_url.txt','r'); print f.read(); f.close(); 二.读取规定长度文件 ...
- golang学习笔记 ----读写文件
使用io/ioutil进行读写文件 ioutil包 其中提到了两个方法: func ReadFile func ReadFile(filename string) ([]byte, error) Re ...
- golang读写文件
1. 标准输入输出 os提供了标准输入输出文件: Stdin = NewFile(uintptr(syscall.Stdin), "/dev/stdin") Stdout = Ne ...
- 系统学习 Java IO (十三)----字符读写 Reader/Writer 及其常用子类
目录:系统学习 Java IO---- 目录,概览 Reader Reader 类是 Java IO API 中所有 Reader 子类的基类. Reader 类似于 InputStream ,除了它 ...
随机推荐
- python之atexit模块的使用
python atexit 模块定义了一个 register 函数,用于在 python 解释器中注册一个退出函数,这个函数在解释器正常终止时自动执行,一般用来做一些资源清理的操作. atexit 按 ...
- Short XSS
Short XSS Crackkay · 2013/08/21 12:17 0x00 背景 关键时候长度不够怎么办? 在实际的情况中如果你不够长怎么办呢?看医生?吃药?做手术?............ ...
- CentOS 7 系统初始化
0.安装系统基础依赖工具包 yum install net-tools gcc-c++ wget lrzsz vim ntpdate cronolog make psmisc 1.修改主机名 cent ...
- 算法---FaceNet+mtcnn的使用记录
FaceNet+mtcnn---ubutntu系统下的使用记录 @WP20190307 由于先配置了FaceNet算法,中途遇到了点问题,单独又配置了mtcnn进行学习,没有深入,蜻蜓点水.今天,在尝 ...
- 拆机联想ideapad s500
这是我第一次拆机,中间也是经历了各种艰难险阻,最后还算是成功.首先,说一下拆机得目的:很简单,为了加一个内存条:下面具体说拆机得步骤: 第一步,在网上查攻略,刚开始的时候,并没有很详细的具体到机型,只 ...
- 说说lock到底锁谁(II)?
摘要 今天在园子里面有园友反馈关于[C#基础]说说lock到底锁谁?文章中lock(this)的问题.后来针对文章中的例子,仔细想了一下,确实不准确,才有了这篇文章的补充,已经对文章中的demo进行修 ...
- 记录截取tableview图的方法
// 截图 - (void)screenShots{ UITableView *shadowView = mainTab; // 开启图片上下文 UIGraphicsBeginImageContext ...
- P5650 基础字符串练习题
设定'0'权值为1,设定'1'权值为-1 然后就是最大子段和 #include <cstdio> #include <algorithm> #include <cstri ...
- [唐胡璐]Selenium技巧- ReportNG替换TestNG默认结果报告
TestNG默认的报告虽然内容挺全,但是展现效果却不太理想,不易阅读。因此我们想利用ReportNG来替代TestNG默认的report。 什么是ReportNG呢?这里不多说,请直接参见:http: ...
- BZOJ 4009: [HNOI2015]接水果 (整体二分+扫描线 树状数组)
整体二分+扫描线 树状数组 具体做法看这里a CODE #include <cctype> #include <cstdio> #include <cstring> ...