当前位置:网站首页>【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)
}
边栏推荐
- ONgDB图数据库与Spark的集成
- I let the database lock the table! Almost fired!
- How can programmers improve the speed of code writing?
- Readis configuration and optimization of NoSQL (final chapter)
- Accounting regulations and professional ethics [6]
- Research Report on market supply and demand and strategy of China's four sided flat bag industry
- ~89 deformation translation
- 手里10万元存款买什么理财产品收益最高?
- 基于check-point机制的任务状态回滚和数据分块任务
- Software Engineer vs Hardware Engineer
猜你喜欢

Filtered off site request to
![[North Asia data recovery] a database data recovery case where the disk on which the database is located is unrecognized due to the RAID disk failure of HP DL380 server](/img/79/3fab19045e1ab2f5163033afaa4309.jpg)
[North Asia data recovery] a database data recovery case where the disk on which the database is located is unrecognized due to the RAID disk failure of HP DL380 server

DIY a low-cost multi-functional dot matrix clock!

How to decrypt worksheet protection password in Excel file

Understand asp Net core - Authentication Based on jwtbearer

Years of training, towards Kata 3.0! Enter the safe container experience out of the box | dragon lizard Technology

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

函數式接口,方法引用,Lambda實現的List集合排序小工具

Readis configuration and optimization of NoSQL (final chapter)

智慧物流园区供应链管理系统解决方案:数智化供应链赋能物流运输行业供应链新模式
随机推荐
~88 running people practice
The content of the source code crawled by the crawler is inconsistent with that in the developer mode
周大福践行「百周年承诺」,真诚服务推动绿色环保
Task state rollback and data blocking tasks based on check point mechanism
Redis: SDS source code analysis
Market trend report, technical innovation and market forecast of electrochromic glass and devices in China and Indonesia
Principle and general steps of SQL injection
Application and Optimization Practice of redis in vivo push platform
NoSQL之readis配置与优化(终章)
SQL implements split
安信证券排名 网上开户安全吗
Years of training, towards Kata 3.0! Enter the safe container experience out of the box | dragon lizard Technology
同构图与异构图CYPHER-TASK设计与TASK锁机制
Congratulations to Mr. Zhang Pengfei, chief data scientist of artefact, for winning the campaign Asia tech MVP 2022
如何为ONgDB核心项目源码做贡献
Hair growth shampoo industry Research Report - market status analysis and development prospect forecast
Practice: fabric user certificate revocation operation process
C# 实现 FFT 正反变换 和 频域滤波
China's plastic processing machinery market trend report, technological innovation and market forecast
Start by counting