Bruce Blog Bruce Blog
首页
  • CentOS
  • Ubuntu-Debian
  • 系统网络
  • 系统辅助工具
  • MySQL
  • Redis
  • Mongodb
  • Docker基础
  • Container基础
  • Kubernetes

    • Kubernetes基础
    • Kubernetes辅助
  • Container-Network
  • Jenkins
  • Gitlab
  • ArgoCD
  • Ansible
  • Terraform
  • AWS
  • MQ
  • NGINX
  • JumpServer
  • 基础
  • 函数模块
  • 框架
  • 基础

    • Golang环境
    • 语法
    • 数据类型与运算符
    • 分支语句
    • 循环语句
    • 数组
    • 切片
    • Map
    • String
    • 函数
    • 包的管理
    • 指针
    • 结构体
    • Go语言中的OOP
    • 方法和接口
    • 错误处理
  • Go进阶

    • Go进阶
  • Go框架

    • Go框架
  • Golang辅助

    • Golang辅助
  • CSS
  • HTML
  • JavaScript
  • 前端辅助
  • 常用命令
  • 性能监控工具
  • Windows下Docker使用
  • 日常学习
  • 其他导航

Bruce Tao

运维界的该溜子
首页
  • CentOS
  • Ubuntu-Debian
  • 系统网络
  • 系统辅助工具
  • MySQL
  • Redis
  • Mongodb
  • Docker基础
  • Container基础
  • Kubernetes

    • Kubernetes基础
    • Kubernetes辅助
  • Container-Network
  • Jenkins
  • Gitlab
  • ArgoCD
  • Ansible
  • Terraform
  • AWS
  • MQ
  • NGINX
  • JumpServer
  • 基础
  • 函数模块
  • 框架
  • 基础

    • Golang环境
    • 语法
    • 数据类型与运算符
    • 分支语句
    • 循环语句
    • 数组
    • 切片
    • Map
    • String
    • 函数
    • 包的管理
    • 指针
    • 结构体
    • Go语言中的OOP
    • 方法和接口
    • 错误处理
  • Go进阶

    • Go进阶
  • Go框架

    • Go框架
  • Golang辅助

    • Golang辅助
  • CSS
  • HTML
  • JavaScript
  • 前端辅助
  • 常用命令
  • 性能监控工具
  • Windows下Docker使用
  • 日常学习
  • 其他导航
  • 基础

  • Go进阶

    • Go进阶
    • File操作
    • IO操作
    • 文件复制
    • 断点续传
    • bufio包
    • ioutil包
      • 遍历目录
      • 并发性Concurrency概念
      • Goroutine初识
      • Goroutine并发模型
      • Runtime包
      • 临界资源安全问题
      • sync包WaitGroup
      • 互斥锁
      • 读写锁
      • Channel通道
      • 关闭通道和通道上范围循环
      • 缓冲通道
      • 定向通道
      • time包中的通道相关函数
      • select语句
      • CSP并发模型
      • Go语言反射(一)
      • Go语言反射(二)
    • Go框架

    • Golang辅助

    • Golang
    • Go进阶
    Bruce
    2022-12-03
    目录

    ioutil包

    # 一、ioutil包

    除了io包可以读写数据,Go语言中还提供了一个辅助工具包就是ioutil.

    • https://golang.google.cn/pkg/io/ioutil/
    • 该包的介绍:Package ioutil implements some I/O utility functions
    import "io/ioutil"
    
    1

    # 二、ioutil包的方法

    // Discard 是一个 io.Writer 接口,调用它的 Write 方法将不做任何事情
    // 并且始终成功返回.
    var Discard io.Writer = devNull(0)
    
    // ReadAll 读取 r 中的所有数据,返回读取的数据和遇到的错误.
    // 如果读取成功,则 err 返回 nil,而不是 EOF,因为 ReadAll 定义为读取
    // 所有数据,所以不会把 EOF 当做错误处理.
    func ReadAll(r io.Reader) ([]byte, error)
    
    // ReadFile 读取文件中的所有数据,返回读取的数据和遇到的错误.
    // 如果读取成功,则 err 返回 nil,而不是 EOF
    func ReadFile(filename string) ([]byte, error)
    
    // WriteFile 向文件中写入数据,写入前会清空文件.
    // 如果文件不存在,则会以指定的权限创建该文件.
    // 返回遇到的错误.
    func WriteFile(filename string, data []byte, perm os.FileMode) error
    
    // ReadDir 读取指定目录中的所有目录和文件(不包括子目录).
    // 返回读取到的文件信息列表和遇到的错误,列表是经过排序的.
    func ReadDir(dirname string) ([]os.FileInfo, error)
    
    // NopCloser 将 r 包装为一个 ReadCloser 类型,但 Close 方法不做任何事情.
    func NopCloser(r io.Reader) io.ReadCloser
    
    // TempFile 在 dir 目录中创建一个以 prefix 为前缀的临时文件,并将其以读
    // 写模式打开.返回创建的文件对象和遇到的错误.
    // 如果 dir 为空,则在默认的临时目录中创建文件(参见 os.TempDir),多次
    // 调用会创建不同的临时文件,调用者可以通过 f.Name() 获取文件的完整路径.
    // 调用本函数所创建的临时文件,应该由调用者自己删除.
    func TempFile(dir, prefix string) (f *os.File, err error)
    
    // TempDir 功能同 TempFile,只不过创建的是目录,返回目录的完整路径.
    func TempDir(dir, prefix string) (name string, err error)
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    # ioutil.ReadFile
    # 调用函数
    // As of Go 1.16, this function simply calls os.ReadFile.
    func ReadFile(filename string) ([]byte, error) {
    	return os.ReadFile(filename)
    }
    
    # 实现方法
    // ReadFile reads the named file 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 ReadFile(name string) ([]byte, error) {
    	f, err := Open(name)
    	if err != nil {
    		return nil, err
    	}
    	defer f.Close()
    
    	var size int
    	if info, err := f.Stat(); err == nil {
    		size64 := info.Size()
    		if int64(int(size64)) == size64 {
    			size = int(size64)
    		}
    	}
    	size++ // one byte for final read at EOF
    
    	// If a file claims a small size, read at least 512 bytes.
    	// In particular, files in Linux's /proc claim size 0 but
    	// then do not work right if read in small pieces,
    	// so an initial read of 1 byte would not work correctly.
    	if size < 512 {
    		size = 512
    	}
    
    	data := make([]byte, 0, size)
    	for {
    		if len(data) >= cap(data) {
    			d := append(data[:cap(data)], 0)
    			data = d[:len(data)]
    		}
    		n, err := f.Read(data[len(data):cap(data)])
    		data = data[:len(data)+n]
    		if err != nil {
    			if err == io.EOF {
    				err = nil
    			}
    			return data, err
    		}
    	}
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    # ioutil.WriteFile
    # 调用函数
    // WriteFile writes data to a file named by filename.
    // If the file does not exist, WriteFile creates it with permissions perm
    // (before umask); otherwise WriteFile truncates it before writing, without changing permissions.
    //
    // As of Go 1.16, this function simply calls os.WriteFile.
    func WriteFile(filename string, data []byte, perm fs.FileMode) error {
    	return os.WriteFile(filename, data, perm)
    }
    
    # 实现方法
    // WriteFile writes data to the named file, creating it if necessary.
    // If the file does not exist, WriteFile creates it with permissions perm (before umask);
    // otherwise WriteFile truncates it before writing, without changing permissions.
    func WriteFile(name string, data []byte, perm FileMode) error {
    	f, err := OpenFile(name, O_WRONLY|O_CREATE|O_TRUNC, perm)
    	if err != nil {
    		return err
    	}
    	_, err = f.Write(data)
    	if err1 := f.Close(); err1 != nil && err == nil {
    		err = err1
    	}
    	return err
    }
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    # ioutil.ReadAll
    # 调用函数
    // ReadAll reads from r until an error or EOF and returns the data it read.
    // A successful call returns err == nil, not err == EOF. Because ReadAll is
    // defined to read from src until EOF, it does not treat an EOF from Read
    // as an error to be reported.
    //
    // As of Go 1.16, this function simply calls io.ReadAll.
    func ReadAll(r io.Reader) ([]byte, error) {
    	return io.ReadAll(r)
    }
    
    
    # 实现方法
    // ReadAll reads from r until an error or EOF and returns the data it read.
    // A successful call returns err == nil, not err == EOF. Because ReadAll is
    // defined to read from src until EOF, it does not treat an EOF from Read
    // as an error to be reported.
    func ReadAll(r Reader) ([]byte, error) {
    	b := make([]byte, 0, 512)
    	for {
    		if len(b) == cap(b) {
    			// Add more capacity (let append pick how much).
    			b = append(b, 0)[:len(b)]
    		}
    		n, err := r.Read(b[len(b):cap(b)])
    		b = b[:len(b)+n]
    		if err != nil {
    			if err == EOF {
    				err = nil
    			}
    			return b, err
    		}
    	}
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34

    # 三、示例代码

    package main
    
    import (
        "io/ioutil"
        "fmt"
        "os"
    )
    
    func main() {
        /*
        ioutil包:
            ReadFile()
            WriteFile()
            ReadDir()
            ..
         */
    
        //1.读取文件中的所有的数据
        //fileName1 := "/Users/ruby/Documents/pro/a/aa.txt"
        //data, err := ioutil.ReadFile(fileName1)
        //fmt.Println(err)
        //fmt.Println(string(data))
    
        //2.写出数据
        //fileName2:="/Users/ruby/Documents/pro/a/bbb.txt"
        //s1:="helloworld面朝大海春暖花开"
        //err:=ioutil.WriteFile(fileName2,[]byte(s1),0777)
        //fmt.Println(err)
    
        //3.
        //s2:="qwertyuiopsdfghjklzxcvbnm"
        //r1:=strings.NewReader(s2)
        //data,_:=ioutil.ReadAll(r1)
        //fmt.Println(data)
    
        //4.ReadDir(),读取一个目录下的子内容:子文件和子目录,但是仅有一层
        //dirName:="/Users/ruby/Documents/pro/a"
        //fileInfos,_:=ioutil.ReadDir(dirName)
        //fmt.Println(len(fileInfos))
        //for i:=0;i<len(fileInfos);i++{
        //  //fmt.Printf("%T\n",fileInfos[i])
        //  fmt.Println(i,fileInfos[i].Name(),fileInfos[i].IsDir())
        //
        //}
    
        // 5.创建临时目录
        dir, err := ioutil.TempDir("/Users/ruby/Documents/pro/a", "Test")
        if err != nil {
            fmt.Println(err)
        }
        defer os.Remove(dir) // 用完删除
        fmt.Printf("%s\n", dir)
    
        // 创建临时文件
        f, err := ioutil.TempFile(dir, "Test")
        if err != nil {
            fmt.Println(err)
        }
        defer os.Remove(f.Name()) // 用完删除
        fmt.Printf("%s\n", f.Name())
    
    }
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    上次更新: 2024/04/09, 16:48:42
    bufio包
    遍历目录

    ← bufio包 遍历目录→

    最近更新
    01
    AWS NAT-NetWork-Firwalld配置(一)
    04-09
    02
    AWS NAT-NetWork-Firwalld配置(二)
    04-09
    03
    kubernetes部署minio对象存储
    01-18
    更多文章>
    Theme by Vdoing | Copyright © 2019-2024 Bruce Tao Blog Space | MIT License
    • 跟随系统
    • 浅色模式
    • 深色模式
    • 阅读模式