当前位置:网站首页> 一文搞懂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语言 文件读写 创建内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!
边栏推荐
- 黑马程序员-软件测试--09阶段2-linux和数据库-31-43修改文件权限字母发的说明,-查找链接修改文件,查找文件命令,链接文件,压缩解压方式,vi编辑器基本使用,
- The explain statement in MySQL queries whether SQL is indexed, and several types in extra collate and summarize
- 为什么最大速度是光速
- Pythagorean number law (any three numbers can meet the conditions of Pythagorean theorem)
- 1009 product of polynomials (25 points) (PAT class a)
- 1011 World Cup betting (20 points) (pat a)
- Niuke Xiaobai monthly race 7 I new Microsoft Office Word document
- 应用实践 | 蜀海供应链基于 Apache Doris 的数据中台建设
- [QNX Hypervisor 2.2用户手册]6.3.1 工厂页和控制页
- Swagger suddenly went crazy
猜你喜欢
Swagger suddenly went crazy
Process of manually encrypt the mass-producing firmware and programming ESP devices
C language - Introduction - Foundation - grammar - process control (VII)
应用实践 | 蜀海供应链基于 Apache Doris 的数据中台建设
记一次 .NET 某工控数据采集平台 线程数 爆高分析
Chrome development tool: what the hell is vmxxx file
JVM系列之对象的创建
English grammar_ Noun - use
abc229 总结(区间最长连续字符 图的联通分量计数)
实战模拟│JWT 登录认证
随机推荐
华为云云商店首页 Banner 资源位申请
The explain statement in MySQL queries whether SQL is indexed, and several types in extra collate and summarize
HDU 1372 & POJ 2243 Knight moves (breadth first search)
Swagger突然发癫
CANN算子:利用迭代器高效实现Tensor数据切割分块处理
Cann operator: using iterators to efficiently realize tensor data cutting and blocking processing
Cbcgpprogressdlgctrl progress bar used by BCG
更强的 JsonPath 兼容性及性能测试之2022版(Snack3,Fastjson2,jayway.jsonpath)
Huawei Nova 10 series supports the application security detection function to build a strong mobile security firewall
Niuke Xiaobai month race 7 F question
Pointnext: review pointnet through improved model training and scaling strategies++
kotlin 基本使用
【历史上的今天】7 月 4 日:第一本电子书问世;磁条卡的发明者出生;掌上电脑先驱诞生
HMM hidden Markov model and code implementation
需求开发思考
What financial products can you buy with a deposit of 100000 yuan?
Process of manually encrypt the mass-producing firmware and programming ESP devices
repeat_ P1002 [NOIP2002 popularization group] cross the river pawn_ dp
Dark horse programmer - software testing - 09 stage 2-linux and database -31-43 instructions issued by modifying the file permission letter, - find the link to modify the file, find the file command,
黑马程序员-软件测试--08阶段2-linux和数据库-23-30-进程端口相关,修改文件权限,端口号信息的获取,程序和进程相关操作,linux命令案例