当前位置:网站首页>【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)
}
边栏推荐
- Configuration instance of Oracle listener server and client
- Hair growth shampoo industry Research Report - market status analysis and development prospect forecast
- Transformer中position encoding实践
- 嵌入式软件架构设计-函数调用
- 线性时间排序
- Redis: SDS source code analysis
- Sequence diagram data modeling and industrial chain analysis
- Blood spitting finishing nanny level series tutorial - play Fiddler bag grabbing tutorial (2) - first meet fiddler, let you have a rational understanding
- 对人胜率84%,DeepMind AI首次在西洋陆军棋中达到人类专家水平
- Capvision Rongying's prospectus in Hong Kong was "invalid": it was strictly questioned by the CSRC and required supplementary disclosure
猜你喜欢

Filtered off site request to

The vscode waveform curve prompts that the header file cannot be found (an error is reported if the header file exists)

Opencv learning -- geometric transformation of image processing

overflow:auto与felx结合的用法

2022年国内云管平台厂商哪家好?为什么?

Capvision Rongying's prospectus in Hong Kong was "invalid": it was strictly questioned by the CSRC and required supplementary disclosure

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

Visual studio 2019 (localdb) mssqllocaldb SQL Server 2014 database version is 852 and cannot be opened. This server supports 782

嵌入式软件架构设计-函数调用

Smart Logistics Park supply chain management system solution: digital intelligent supply chain enables a new supply chain model for the logistics transportation industry
随机推荐
ONgDB图数据库与Spark的集成
FIREBIRD使用经验总结
TypeError: list indices must be integers or slices, not str
Redis: SDS source code analysis
C# 实现 FFT 正反变换 和 频域滤波
高度剩余法
Congratulations to Mr. Zhang Pengfei, chief data scientist of artefact, for winning the campaign Asia tech MVP 2022
.Net 应用考虑x64生成
基于wifi控制的51单片机温度报警器
Hair and fuzz interceptor Industry Research Report - market status analysis and development prospect forecast
[Previous line repeated 995 more times]RecursionError: maximum recursion depth exceeded
Accounting regulations and professional ethics [9]
时序图数据建模与产业链分析
安信证券排名 网上开户安全吗
Market trend report, technical innovation and market forecast of taillight components in China
Readis configuration and optimization of NoSQL (final chapter)
Implement graph data construction task based on check point
表单传递时,如何隐式将值传过去
DC-2靶场搭建及渗透实战详细过程(DC靶场系列)
Understand Alibaba cloud's secret weapon "dragon architecture" in the article "science popularization talent"