Golang中的文件操作

1.打开文件和关闭文件

Go 复制代码
package main

import (
	"fmt"
	"os"
)

func main() {
	//打开文件
	file, err := os.Open("file/wordtest.txt")
	if err != nil {
		fmt.Println("open file err=", err)
	}

	//file就是一个指针*file
	fmt.Printf("file=%v\n", file)

	//关闭文件
	err = file.Close()
	if err != nil {
		fmt.Println("close file err=", err)
	}
}
Go 复制代码
file=&{0xc000068a00}

2.带缓冲的Reader读取文件

Go 复制代码
package main

//带缓冲的reader读文件
import (
	"bufio"
	"fmt"
	"io"
	"os"
)

//带缓冲的Reader读文件

func main() {
	file, err := os.Open("file/wordtest.txt")
	if err != nil {
		fmt.Println("open file err=", err)
	}
	//当函数推出时,要及时的关闭file
	defer file.Close()

	//创建reader
	reader := bufio.NewReader(file)
	//循环读取文件的内容
	for {
		//读到一个换行结束
		str, err := reader.ReadString('\n')
		//文件的末尾
		if err == io.EOF {
			break
		}
		fmt.Print(str)
	}

	fmt.Println("文件读取结束")
}
Go 复制代码
hello,world
珠海!abc!Golang!
Go,hello,world
文件读取结束

3.一次性读取文件

Go 复制代码
package main

//一次性读取文件
import (
	"fmt"
	"os"
)

// 一次性读取文件
func main() {
	file := "file/wordtest.txt"
	content, err := os.ReadFile(file)
	if err != nil {
		fmt.Printf("read file err=%v", err)
	}
	//[]byte
	fmt.Printf("%v\n", content)
	fmt.Printf("%s\n", string(content))
}
Go 复制代码
[104 101 108 108 111 44 119 111 114 108 100 13 10 231 143 160 230 181 183 239 188 129 97 98 99 33 71 111 108 97 110 103 
33 13 10 71 111 44 104 101 108 108 111 44 119 111 114 108 100 13 10]
hello,world
珠海!abc!Golang!
Go,hello,world

4.创建文件写入内容

Go 复制代码
package main

//创建文件,写入内容
import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	//创建一个新文件,写入5句"hello jinitaimei"
	//1.打开文件
	filePath := "./file/wordtest2.txt"
	file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		fmt.Printf("open file err=%v\n", err)
		return
	}
	//
	defer file.Close()
	str := "hello jinitaimei\n"
	//写入时使用带缓存的*writer
	writer := bufio.NewWriter(file)
	for i := 0; i < 5; i++ {
		writer.WriteString(str)
	}

	//因为Writer是带缓存的,因此再调用WriterString方法时,其实内容是先写入到缓存,所以
	//用flush把缓存的数据真正写入到文件
	writer.Flush()
}
Go 复制代码
wordtest2.txt的文件内容:
hello jinitaimei
hello jinitaimei
hello jinitaimei
hello jinitaimei
hello jinitaimei

5.打开一个存在的文件,把原来的内容覆盖新的内容

Go 复制代码
package main

import (
	"bufio"
	"fmt"
	"os"
)

//打开一个存在的文件,把原来的内容覆盖为10句"Hi,Xiamen"

func main() {
	//创建一个新文件,写入5句"hello jinitaimei"
	//1.打开文件
	filePath := "./file/wordtest2.txt"
	//O_TRUNC:清理内容
	file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_TRUNC, 0666)
	if err != nil {
		fmt.Printf("open file err=%v\n", err)
		return
	}
	//
	defer file.Close()
	str := "hello Xiamen\r\n"
	//写入时使用带缓存的*writer
	writer := bufio.NewWriter(file)
	for i := 0; i < 10; i++ {
		writer.WriteString(str)
	}

	//因为Writer是带缓存的,因此再调用WriterString方法时,其实内容是先写入到缓存,所以
	//用flush把缓存的数据真正写入到文件
	writer.Flush()
}

6.对已经存在的文件,追加内容

Go 复制代码
package main

import (
	"bufio"
	"fmt"
	"os"
)

// 对已经存在的文件,追加内容
func main() {
	filePath := "./file/wordtest2.txt"
	file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		fmt.Println("open file err=%v\n", err)
		return
	}

	//及时关闭file指针
	defer file.Close()

	str := "Humans, I want the clear,pollution-free water!\r\n"
	//使用带缓存的*Writer
	writer := bufio.NewWriter(file)
	for i := 0; i < 10; i++ {
		writer.WriteString(str)
	}

	writer.Flush()
}

7.把原来的内容读取出来,再往文件追加几句话

Go 复制代码
package main

//把原来的内容读取出来,追加几句话
import (
	"bufio"
	"fmt"
	"io"
	"os"
)

// 对已经存在的文件,追加内容
func main() {
	filePath := "./file/wordtest2.txt"
	file, err := os.OpenFile(filePath, os.O_RDWR|os.O_APPEND, 0666)
	if err != nil {
		fmt.Println("open file err=%v\n", err)
		return
	}

	//及时关闭file指针
	defer file.Close()
	//先读取原来文件的内容,显示在终端
	reader := bufio.NewReader(file)
	for {
		str2, err := reader.ReadString('\n')
		//文件末尾
		if err == io.EOF {
			break
		}
		fmt.Print(str2)
	}

	str := "Sweet dolphins, I wish you all peace.\r\n"
	//使用带缓存的*Writer
	writer := bufio.NewWriter(file)
	for i := 0; i < 5; i++ {
		writer.WriteString(str)
	}

	writer.Flush()
}
Go 复制代码
终端:
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!

文件:
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Sweet dolphins, I wish you all peace.
Sweet dolphins, I wish you all peace.
Sweet dolphins, I wish you all peace.
Sweet dolphins, I wish you all peace.
Sweet dolphins, I wish you all peace.

8.把一个文件的内容追加到另一个文件中

Go 复制代码
package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	//1.将word1.txt的内容读到内存
	//2.将word1.txt的内容写入word2.txt
	filePath1 := "./file/word1.txt"
	filePath2 := "./file/word2.txt"
	content, err := os.ReadFile(filePath1)
	if err != nil {
		//说明文件有错误
		fmt.Printf("read file err=%v\n", err)
		return
	}

	word2_file, err := os.OpenFile(filePath2, os.O_RDWR|os.O_APPEND, 0666)
	writer := bufio.NewWriter(word2_file)
	writer.WriteString(string(content))
	writer.Flush()

}
Go 复制代码
word1.txt:
When spring comes, all the seeds begin to burgeon.

word2.txt:
People wait in the lounge for boarding.

运行结果:
People wait in the lounge for boarding.When spring comes, all the seeds begin to burgeon.

9.拷贝文件到另一个目录中

Go 复制代码
package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

// 将.jpg从D盘拷贝到E盘
//
//	<----
func CopyFile(dstFileName string, srcFileName string) (written int64, err error) {
	srcFile, err := os.Open(srcFileName)
	if err != nil {
		fmt.Printf("open file err=%v\n", err)
	}
	//通过srcFile获取的Reader
	reader := bufio.NewReader(srcFile)

	//打开dstFile
	dstFile, err := os.OpenFile(dstFileName, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		fmt.Printf("open file err=%v\n", err)
	}
	//通过dstFile获取到Writer
	writer := bufio.NewWriter(dstFile)
	//<---
	return io.Copy(writer, reader)
}

func main() {
	//调用CopyFile完成文件拷贝
	srcFile := "d:/goldpig.jpg"
	dstFile := "e:/goldpig.jpg"
	_, err := CopyFile(dstFile, srcFile)
	if err == nil {
		fmt.Println("拷贝完成")
	} else {
		fmt.Printf("拷贝错误 err=%v\n", err)
	}
}

10.统计文件中不同类型的字符的数量

Go 复制代码
package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

//统计文件中不同类型的字符个数

// 定义一个结构体,用于保存统计结果
type CharCount struct {
	ChCount    int //记录英文个数
	NumCount   int //记录数字的个数
	SpaceCount int //记录空格的个数
	OtherCount int //记录其他字符个数
}

func main() {
	//打开一个文件,创一个Reader
	//每读取一行,就统计该行有多少个英文、数字、空格和其他字符
	//然后将结果保存到一个结构体
	fileName := "./file/abc.txt"
	file, err := os.Open(fileName)
	if err != nil {
		fmt.Printf("open file err=%v\n", err)
		return
	}
	defer file.Close()
	//定义个CharCount示例
	var count CharCount
	//创建一个Reader
	reader := bufio.NewReader(file)

	//开始循环的读取fileName的内容
	for {
		str, err := reader.ReadString('\n')
		//读到文件末尾就退出
		if err == io.EOF {
			break
		}
		//遍历str,进行统计
		for _, v := range str {
			switch {
			case v >= ('a') && v <= 'z':
				fallthrough
			case v >= 'A' && v <= 'Z':
				count.ChCount++
			case v == ' ' || v == '\t':
				count.SpaceCount++
			case v >= '0' && v <= '9':
				count.NumCount++
			default:
				count.OtherCount++
			}
		}
	}

	//输出统计的结果看看是否正确
	fmt.Printf("字符的个数=%v 数字的个数=%v 空格的个数=%v 其他字符的个数=%v\n",
		count.ChCount, count.NumCount, count.SpaceCount, count.OtherCount)
}
Go 复制代码
文件内容:
ab123 89popj
yy89 hello

运行结果:
字符的个数=13 数字的个数=7 空格的个数=2 其他字符的个数=4
相关推荐
掘金者阿豪27 分钟前
🚀 CentOS Stream 9服务器Docker部署KWDB:从零到跨模查询实战全记录
后端
yang_xin_yu33 分钟前
一文带你精通泛型PECS原则与四大核心函数式接口
后端
孟陬43 分钟前
国外技术周刊 #1:Paul Graham 重新分享最受欢迎的文章《创作者的品味》、本周被划线最多 YouTube《如何在 19 分钟内学会 AI》、为何我不
java·前端·后端
树獭叔叔44 分钟前
13-KV Cache与位置编码表:大模型推理加速的核心技术
后端·aigc·openai
想用offer打牌1 小时前
一站式了解四种限流算法
java·后端·go
嘻哈baby1 小时前
用 C++ 写线程池是怎样一种体验?
后端
嘻哈baby1 小时前
SQL Server 和 Oracle 以及 MySQL 有哪些区别?
后端
绝无仅有1 小时前
Redis过期删除与内存淘汰策略详解
后端·面试·架构
武子康1 小时前
大数据-237 离线数仓 - Hive 广告业务实战:ODS→DWD 事件解析、广告明细与转化分析落地
大数据·后端·apache hive
绝无仅有1 小时前
Redis大Key问题排查与解决方案全解析
后端·面试·架构