当前位置:网站首页>【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)
}
边栏推荐
- Can you really use MySQL explain?
- 程序员怎么才能提高代码编写速度?
- 基于check-point机制的任务状态回滚和数据分块任务
- Anta is actually a technology company? These operations fool netizens
- Visual Studio 2019 (LocalDB)MSSQLLocalDB SQL Server 2014 数据库版本为852无法打开,此服务器支持782
- Detailed process of DC-2 range construction and penetration practice (DC range Series)
- .Net 应用考虑x64生成
- D3D11_ Chili_ Tutorial (2): draw a triangle
- Start by counting
- Solution du système de gestion de la chaîne d'approvisionnement du parc logistique intelligent
猜你喜欢
基于wifi控制的51单片机温度报警器
智慧物流园区供应链管理系统解决方案:数智化供应链赋能物流运输行业供应链新模式
建筑建材行业经销商协同系统解决方案:赋能企业构建核心竞争力
~89 deformation translation
[North Asia data recovery] a database data recovery case where the partition where the database is located is unrecognized due to the RAID disk failure of HP DL380 server
GO开发:如何利用Go单例模式保障流媒体高并发的安全性?
What is torch NN?
"Cannot initialize Photoshop because the temporary storage disk is full" graphic solution
Go development: how to use go singleton mode to ensure the security of high concurrency of streaming media?
How to decrypt worksheet protection password in Excel file
随机推荐
周大福践行「百周年承诺」,真诚服务推动绿色环保
多年锤炼,迈向Kata 3.0 !走进开箱即用的安全容器体验之旅| 龙蜥技术
TypeError: not enough arguments for format string
祝贺Artefact首席数据科学家张鹏飞先生荣获 Campaign Asia Tech MVP 2022
Capvision Rongying's prospectus in Hong Kong was "invalid": it was strictly questioned by the CSRC and required supplementary disclosure
新的职业已经出现,怎么能够停滞不前 ,人社部公布建筑新职业
Accounting regulations and professional ethics [11]
高度剩余法
Oracle监听器Server端与Client端配置实例
线程池的使用和原理
SQL implements split
Vscode setting outline shortcut keys to improve efficiency
L1-072 scratch lottery
Principle and general steps of SQL injection
Market trend report, technical innovation and market forecast of taillight components in China
China's plastic processing machinery market trend report, technological innovation and market forecast
Understand ThreadLocal in one picture
D3D11_ Chili_ Tutorial (2): draw a triangle
[Chongqing Guangdong education] National Open University spring 2019 1248 public sector human resource management reference questions
科普达人丨一文看懂阿里云的秘密武器“神龙架构”