读文件:

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. .net core 根据数据库生成实体类

    微软最近几年在跨平台上不断发力,很多.net程序员也摩拳擦掌,对微软寄以厚望.就在最近,微软还推出了asp .net core2.0预览版. 通过对.net core的简单尝试,我发现以往我们开发MV ...

  2. javaIO——BufferedReader

    今天来学习一下 java.io.BufferedReader ,从命名可以看出,跟前面学习的 StringReader 和 CharArrayReader 有些不一样,这些都是按照数据源类型命名,Bu ...

  3. Python 数字(函数)

    Python支持4种不同数值类型: 整型(Int) - 通常被称为是整型或整数,是正或负整数,不带小数点. 长整型(long integers) - 无限大小的整数,整数最后是一个大写或小写的L. 浮 ...

  4. 【温故知新】php 魔术方法

    <?php class Magic{ private $name; /** *构造方法,在类被实例化时自动调用,一般用于初始化操作 */ public function __construct( ...

  5. css优先级及其对应的权重

    1.选择器的优先级 !important>内联选择器(style)>id选择器>类选择器 | 属性选择器 | 伪类选择器 > 元素选择器>通配符(*) 2.选择器的权重( ...

  6. canvas学习之初级运用

    <html> <head> <meta charset=utf-8> <title>绘制简单图形</title> <style typ ...

  7. 如何部署自定义的servlet

    1 首先找到与exlipse绑定的tomcat安装位置 2 打开web.xml添加如下信息: <display-name>servletDemo</display-name> ...

  8. linux环境下安装python3的方法(转)

    Linux 安装python3.7.0   我这里使用的时centos7-mini,centos系统本身默认安装有python2.x,版本x根据不同版本系统有所不同,可通过 python --V 或 ...

  9. 使用nodejs创建Marketing Cloud的contact数据

    源代码如下: var config = require("./mcConfig"); var request = require('request'); var url = con ...

  10. vue常用知识点

    vue中图片路径写法 <img :src="avatorSrc" alt=""> <img :src="avatorSrc2&quo ...