欢迎您的访问
专注架构,Java,数据结构算法,Python技术分享

golang教程(十五):文件操作

一、文件的基本介绍

  1. 文件的概念
    文件,对我们并不陌生,文件是数据源(保存数据的地方)的一种,比如大家经常使用的 word 文档,txt 文
    件,excel 文件…都是文件。文件最主要的作用就是保存数据,它既可以保存一张图片,也可以保持视频,声
    音…
  2. 输入流和输出流
    在这里插入图片描述
  3. os.File 封装所有文件相关操作,File 是一个结构体
    在这里插入图片描述

二、文件的基本操作

1、打开文件和关闭文件

在这里插入图片描述
在这里插入图片描述
示例:

func main() {
	//默认路径是从项目的根路径开始的
	file, e := os.Open("file/test.txt")
	if e != nil{
		fmt.Println("文件打开失败!!")
	}
	e = file.Close()
	if e != nil{
		fmt.Println("文件关闭失败!!")
	}
}

 

2、读文件操作

1) bufio

读取文件的内容并显示在终端(带缓冲区的方式),使用 os.Open, file.Close, bufio.NewReader(), reader.ReadString 函数和方法.

func main() {
	//默认路径是从项目的根路径开始的
	file, e := os.Open("file/test.txt")
	if e != nil {
		fmt.Println("文件打开失败!!")
	}
	//main方法结束时关闭文件
	defer func() {
		i := file.Close()
		if i != nil {
			fmt.Println("文件关闭失败!!")
		}
	}()
	reader := bufio.NewReader(file)
	for {
		line, isPrefix, e := reader.ReadLine()
		if  e == io.EOF {
			fmt.Println("结束:", e)
			break
		} else {
			fmt.Println(isPrefix,string(line))
		}
	}
}

 

说明:
在这里插入图片描述

reader := bufio.NewReader(file)
	for{
		str, e := reader.ReadString('\n')
		if len(str) == 0{
			break
		}
		if e !=nil && e != io.EOF{
			break
		}
		fmt.Println(str)
	}

 

说明:
在这里插入图片描述

2) ioutil

读取文件的内容并显示在终端(使用 ioutil 一次将整个文件读入到内存中),这种方式适用于文件
不大的情况。相关方法和函数(ioutil.ReadFile)

func main() {
	//默认路径是从项目的根路径开始的
	filePath := "file/test.txt"
	bytes, e := ioutil.ReadFile(filePath)
	if e!=nil{
		fmt.Printf("读取文件%v出错了\n",filePath)
		return
	}
	fmt.Println(string(bytes))
}

 

说明:
在这里插入图片描述

3、写文件操作

1)、基本介绍-os.OpenFile 函数
在这里插入图片描述

  • 第一个参数name:文件路径名称
  • 第二个参数flag:文件打开的模式(可以组合)
    在这里插入图片描述
  • 第三个参数perm:权限控制(系统)
    权限取值范围:0~7
    0:没有任何权限
    1:执行权限()如果文件是可执行文件,是可以运行的
    2:写权限
    3:写权限和执行权限
    4:读权限
    5:读权限和执行权限
    6:读权限和写权限
    7:读权限、写权限和执行权限

一般选择6
在这里插入图片描述
2)、向里文件数据

  • 场景一
    新建文件并写入数据
func main() {
	//默认路径是从项目的根路径开始的
	filePath := "file/test.txt"
	//O_CREATE创建和O_EXCL存在报错 (保证文件是新建的)O_WRONLY(只写,为了后面将内容写入文件)
	file, e := os.OpenFile(filePath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0666)
	defer func() {
		if i := file.Close();i!=nil{
			fmt.Println("文件关闭失败!!")
		}
	}()
	if e!=nil{
		fmt.Println("文件创建失败!!")
		return
	}
	writer := bufio.NewWriter(file)
	nn, e := writer.Write([]byte("hello golang"))
	if e !=nil{
		fmt.Println("内容写入缓冲区失败!!")
		return
	}
	e = writer.Flush()
	if e !=nil{
		fmt.Println("内容刷入文件失败!!")
		return
	}
	fmt.Printf("文件写入了%v字节数据",nn)

}

 

  • 场景二
    覆盖上面写的内容
func main() {
	//默认路径是从项目的根路径开始的
	filePath := "file/test.txt"
	file, e := os.OpenFile(filePath, os.O_WRONLY, 0666)
	defer func() {
		if i := file.Close();i!=nil{
			fmt.Println("文件关闭失败!!")
		}
	}()
	if e!=nil{
		fmt.Println("文件创建失败!!")
		return
	}
	writer := bufio.NewWriter(file)
	nn, e := writer.Write([]byte("hello world"))
	if e !=nil{
		fmt.Println("内容写入缓冲区失败!!")
		return
	}
	e = writer.Flush()
	if e !=nil{
		fmt.Println("内容刷入文件失败!!")
		return
	}
	fmt.Printf("文件写入了%v字节数据",nn)

}

 

注:文件内容变为

hello worldg

 

后面都了个g,其实是覆盖了前面11个字节第12个没有覆盖,应为hello world只有11个字节

  • 场景三
    向文件中追加内容(不覆盖原先的内容)
func main() {
	//默认路径是从项目的根路径开始的
	filePath := "file/test.txt"
	file, e := os.OpenFile(filePath, os.O_WRONLY | os.O_APPEND, 0666)
	defer func() {
		if i := file.Close();i!=nil{
			fmt.Println("文件关闭失败!!")
		}
	}()
	if e!=nil{
		fmt.Println("文件创建失败!!")
		return
	}
	writer := bufio.NewWriter(file)
	nn, e := writer.Write([]byte("|||ABC||DEF"))
	if e !=nil{
		fmt.Println("内容写入缓冲区失败!!")
		return
	}
	e = writer.Flush()
	if e !=nil{
		fmt.Println("内容刷入文件失败!!")
		return
	}
	fmt.Printf("文件写入了%v字节数据",nn)

}

 

3)ioutil
在这里插入图片描述

func main() {
	//默认路径是从项目的根路径开始的
	filePath := "file/test.txt"
	e := ioutil.WriteFile(filePath, []byte("hello golang"), 0666)
	if e!=nil{
		fmt.Println("写文件出错了")
	}
}

 

文件内容变为:hello golang

4)文件其他操作
在这里插入图片描述

  • 判断是否存在
func main() {
	//默认路径是从项目的根路径开始的
	filePath := "file/test.txt"
	_, e := os.Stat(filePath)
	if e==nil || os.IsExist(e)  {
		fmt.Printf("%v exist !!\n",filePath)
	}
	if os.IsNotExist(e) {
		fmt.Printf("%v not exist !!\n",filePath)
	}
}

 

  • 删除文件
func main() {
	//默认路径是从项目的根路径开始的
	filePath := "file/test.txt"
	e := os.Remove(filePath)
	if e!=nil{
		fmt.Println("remove failed!!")
	}
}

 

  • 打印指定目录下 的所有文件路径名称
func read(path string) {
	//获取当前目录的状态信息
	info, _ := os.Stat(path)
	//判断是目录还是文件
	if ! info.IsDir() {
		fmt.Println(path)
		return
	}
	infos, _ := ioutil.ReadDir(path)
	//循环去除目录下的文件
	for _, f := range infos {
		s := path + "/" + f.Name()
		read(s)
	}
}

func main() {
	read("reflect")
}

作者:iRich_全栈 | 来源:http://39sd.cn/E9F10

赞(1) 打赏
版权归原创作者所有,任何形式转载请联系作者;码农code之路 » golang教程(十五):文件操作

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏