当前位置:网站首页> 一文搞懂Go语言中文件的读写与创建
一文搞懂Go语言中文件的读写与创建
2022-07-04 18:39:00 【1024问】
1. 文件的打开与关闭
1.1 os.open
1.2 os.OpenFile() 指定模式打开文件
2. 文件的读取
2.1 打开文件的方式读取文件中的数据
2.2 使用 bufio 整行读取文件
3. 写入文件操作
3.1 file.Write 与 file.WriteString
3.2 bufio.NewWriter
3.3 ioUtil 工具类
1. 文件的打开与关闭1.1 os.openos.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("文件打开出现异常")}// 封装为 bufioreader := 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)}
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// 基于缓存操作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()
// 使用工具类 打开文件,写入文件一气呵成err := ioutil.WriteFile("3.text", []byte("工具类写入内容"), 0666)if err != nil {fmt.Println("程序运行出现异常", err)}
到此这篇关于一文搞懂Go语言中文件的读写与创建的文章就介绍到这了,更多相关Go语言 文件读写 创建内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!
边栏推荐
- 如何让你的小游戏适配不同尺寸的手机屏幕
- c# .net mvc 使用百度Ueditor富文本框上传文件(图片,视频等)
- The explain statement in MySQL queries whether SQL is indexed, and several types in extra collate and summarize
- Informatics Olympiad 1336: [example 3-1] find roots and children
- 更强的 JsonPath 兼容性及性能测试之2022版(Snack3,Fastjson2,jayway.jsonpath)
- Explicit random number
- Prometheus installation
- BCG 使用之CBCGPProgressDlg进度条使用
- 被奉为经典的「金字塔原理」,教给我们哪些PPT写作技巧?
- 漫谈客户端存储技术之Cookie篇
猜你喜欢
Detailed explanation of Audi EDI invoice message
Pytoch learning (4)
Creation of JVM family objects
应用实践 | 蜀海供应链基于 Apache Doris 的数据中台建设
C # use stopwatch to measure the running time of the program
多表操作-外连接查询
C server log module
同事的接口文档我每次看着就头大,毛病多多。。。
Employment prospects and current situation of Internet of things application technology
记一次 .NET 某工控数据采集平台 线程数 爆高分析
随机推荐
node_ Exporter deployment
Optimization cases of complex factor calculation: deep imbalance, buying and selling pressure index, volatility calculation
Introduction to ACM combination counting
【历史上的今天】7 月 4 日:第一本电子书问世;磁条卡的发明者出生;掌上电脑先驱诞生
Double colon function operator and namespace explanation
kotlin 基本数据类型
Cbcgptabwnd control used by BCG (equivalent to MFC TabControl)
Employment prospects and current situation of Internet of things application technology
Huawei Nova 10 series supports the application security detection function to build a strong mobile security firewall
Kotlin basic data type
1002. A+b for Polynomials (25) (PAT class a)
Niuke Xiaobai month race 7 F question
公司要上监控,Zabbix 和 Prometheus 怎么选?这么选准没错!
JVM系列之对象的创建
Neural network IOT platform construction (IOT platform construction practical tutorial)
Swagger suddenly went crazy
上线首月,这家露营地游客好评率高达99.9%!他是怎么做到的?
1005 spell it right (20 points) (pat a)
What does the neural network Internet of things mean? Popular explanation
HMM隐马尔可夫模型最详细讲解与代码实现