当前位置:网站首页>【Go ~ 0到1 】 第六天 文件的读写与创建
【Go ~ 0到1 】 第六天 文件的读写与创建
2022-07-04 15:10:00 【秋日的晚霞】
1. 文件的打开与关闭
1.1 os.open
os.open 函数能打开一个文件 调用 close() 方法 关闭文件
//打开文件
open, err := os.Open("./1.text")
if err != nil {
//打印异常信息
fmt.Println("open file err", err)
}
fmt.Println("文件获取完毕")
//没有出现异常,关闭文件
open.Close()
为了防止忘记关闭文件,通常都将关闭文件的代码写在 defer中
//打开文件
open, err := os.Open("./1.text")
defer func() {
if open != nil {
// 关闭文件
open.Close()
}
}()
if err != nil {
//打印异常信息
fmt.Println("open file err", err)
}
fmt.Println("文件获取完毕")
1.2 os.OpenFile() 指定模式打开文件
func OpenFile(name string, flag int, perm FileMode) (*File, error) {
...
}
其中:
name:要打开的文件名 flag:打开文件的模式。 模式有以下几种:
| 模式 | 含义 |
|---|---|
| os.O_WRONLY | 只写 |
| os.O_CREATE | 创建文件 |
| os.O_RDONLY | 只读 |
| os.O_RDWR | 读写 |
| os.O_TRUNC | 清空 |
| os.O_APPEND | 追加 |
perm:文件权限,一个八进制数。r(读)04,w(写)02,x(执行)01。
2. 文件的读取
2.1 打开文件的方式读取文件中的数据
//首先需要打开一个文件
open, err := os.Open("./1.text")
defer func() {
e := recover()
if e != nil {
fmt.Println("打开文件出现了异常", e)
}
}()
if err != nil {
// 如果有异常 没必要往下走了 抛出
panic(err)
}
//如果没有异常
//创建 字节切片
bytes := make([]byte, 1024)
defer func() {
e := recover()
if e != nil {
fmt.Println("读取文件出现了异常", e)
}
}()
for {
//循环读
_, err := open.Read(bytes)
if err != nil {
panic(err)
}
//打印结果
fmt.Println(string(bytes))
}
2.2 使用 bufio 整行读取文件
bufio 是在file的基础上封装了一层API , 支持更多的功能
//同样的首先打开一个文件
file, err := os.Open("./1.text")
defer recover()
if err != nil {
panic("文件打开出现异常")
}
// 封装为 bufio
reader := bufio.NewReader(file)
defer recover()
for {
//读到指定字符串换一行
line, _, err := reader.ReadLine()
if err != nil {
if err == io.EOF {
fmt.Println("文件读写完毕")
break
}
panic("文件读取出现异常")
}
fmt.Println(string(line))
}
fmt.Println("程序运行结束")
func main() {
file, err := os.OpenFile("xx.txt", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
}
2.3 ioutil 一次读取整个文件
3. 写入文件操作
无论是文件读取还是文件写入 都是需要先打开文件 再进行操作
3.1 file.Write 与 file.WriteString
// 首先打开文件 O_RDWR 读写权限 O_TRUNC 清空文件 0 开头表示八进制 666表示 当用用户 当前组 其他用户 都是可读可写权限
file, err := os.OpenFile("1.text", os.O_RDWR|os.O_TRUNC, 0666)
if err != nil {
fmt.Printf("打开文件出现异常 %v", err)
}
defer file.Close()
// 返回 写入的字节数
write, err := file.Write([]byte("测试文件写入 \n"))
file.WriteString("一次写入整个字符串")
if err != nil {
fmt.Println(err)
}
fmt.Println(write)
3.2 bufio.NewWriter
使用 bufio 一定要调用刷新
// 基于缓存操作
file, err := os.OpenFile("2.text", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
if err != nil {
panic(err)
}
defer func() {
file.Close()
if e := recover(); e != nil {
fmt.Printf("异常 : 打开文件出现异常 %v", e)
}
}()
// 使用 bufio 基于缓存操作io流
// 需要传入 一个 io 接口包下的 Writer 接口实现类 而 file 实现了该 方法
writer := bufio.NewWriter(file)
writer.WriteString(" 写入缓存字符串内容 2")
//需要将缓存中的数据刷新到硬盘上
writer.Flush()

3.3 ioUtil 工具类
// 使用工具类 打开文件,写入文件一气呵成
err := ioutil.WriteFile("3.text", []byte("工具类写入内容"), 0666)
if err != nil {
fmt.Println("程序运行出现异常", err)
}
边栏推荐
- Maximum subarray and matrix multiplication
- 话里话外:流程图绘制初级:六大常见错误
- MFC implementation of ACM basic questions encoded by the number of characters
- 电子元器件B2B商城系统开发:赋能企业构建进销存标准化流程实例
- Firebird experience summary
- The content of the source code crawled by the crawler is inconsistent with that in the developer mode
- Some fields of the crawler that should be output in Chinese are output as none
- [Previous line repeated 995 more times]RecursionError: maximum recursion depth exceeded
- China's plastic processing machinery market trend report, technological innovation and market forecast
- China's roof ladder market trend report, technological innovation and market forecast
猜你喜欢

Object. Usage of keys()

~89 deformation translation

GO开发:如何利用Go单例模式保障流媒体高并发的安全性?

Understand asp Net core - Authentication Based on jwtbearer

S2b2b solution for lighting industry: efficiently enable the industrial supply chain and improve the economic benefits of enterprises

Opencv learning -- geometric transformation of image processing

"Cannot initialize Photoshop because the temporary storage disk is full" graphic solution

智慧物流园区供应链管理系统解决方案:数智化供应链赋能物流运输行业供应链新模式

DC-2靶场搭建及渗透实战详细过程(DC靶场系列)

Object.keys()的用法
随机推荐
Understand Alibaba cloud's secret weapon "dragon architecture" in the article "science popularization talent"
时钟轮在 RPC 中的应用
Go language loop statement (under Lesson 10)
How to decrypt worksheet protection password in Excel file
中位数与次序统计量
Accounting regulations and professional ethics [9]
Opencv learning -- arithmetic operation of image of basic operation
How to contribute to the source code of ongdb core project
照明行业S2B2B解决方案:高效赋能产业供应链,提升企业经济效益
Accounting regulations and professional ethics [6]
Height residual method
Understand asp Net core - Authentication Based on jwtbearer
go-micro教程 — 第二章 go-micro v3 使用Gin、Etcd
2021 Google vulnerability reward program review
World Environment Day | Chow Tai Fook serves wholeheartedly to promote carbon reduction and environmental protection
Daily notes~
Object. Usage of keys()
力扣今日题-1200. 最小绝对差
Understand ThreadLocal in one picture
Median and order statistics