当前位置:网站首页>Go对文件操作
Go对文件操作
2022-04-23 17:51:00 【刘远山】
目录

文件读写
文件读操作
1)文件打开与关闭
简易方式打开一个文件,对文件操作,一秒后关闭
package main
import (
"fmt"
"os"
"time"
)
func main() {
file, err := os.Open("D:/go_work/src/demo/1.json")
if err == nil {
fmt.Println("文件打开成功")
} else {
fmt.Println("文件打开失败,err=", err)
return
}
defer func() {
file.Close()
fmt.Println("文件已关闭")
}()
fmt.Println("对文件操作", file)
time.Sleep(1 * time.Second)
}
2)带缓冲的文件读入
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func main() {
//以只读模式打开文件(0666代表所有人都有读写权限)
file, err := os.OpenFile("D:/go_work/src/demo/1.json", os.O_RDONLY, 0666)
//判断文件打开是否成功
if err == nil {
fmt.Println("文件打开成功")
} else {
fmt.Println("文件打开失败,err=", err)
return
}
//延时(函数返回前)关闭文件-函数返回前会先执行defer引导的语句
defer func() {
file.Close()
fmt.Println("文件已关闭")
}()
//创建该文件的缓冲读取器
reader := bufio.NewReader(file)
//循环读入数据
for {
//每次读入一行
str, err := reader.ReadString('\n')
//判断读入是否成功
if err == nil {
//打印读入的字符串
fmt.Println(str)
} else {
if err == io.EOF {
//已到文件末尾,跳出读取循环
fmt.Println("已到文件末尾!")
break
} else {
//有其它异常,打印异常并结束程序
fmt.Println("读取失败,err=", err)
return
}
}
}
fmt.Println("文件读取完毕!")
}
3)便捷读取文件
package main
import (
"fmt"
"os"
)
func main() {
bytes, err := os.ReadFile("D:/go_work/src/demo/1.json")
if err == nil {
contentStr := string(bytes)
fmt.Println(contentStr)
} else {
fmt.Println("读取失败,err=", err)
}
}
文件写操作
1)缓冲式写入
package main
import (
"bufio"
"fmt"
"os"
)
/*以【创-写-追加】或【创-写-覆盖】方式打开一个文件,缓冲式写出几行数据,倒干缓冲区后退出;*/
func main() {
//打开指定文件,模式:不存在就创建+只写+追加,生成的文件的权限是-rw-rw-rw-
file, err := os.OpenFile("D:/go_work/src/demo/1.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
//如果有异常直接打印退出
if err != nil {
fmt.Println("文件打开失败,err=", err)
return
}
//延时关闭文件
defer func() {
file.Close()
fmt.Println("文件已关闭")
}()
//创建文件的缓冲写出器
writer := bufio.NewWriter(file)
//分批次地写出一些数据
writer.WriteString("测试\n")
//倒干缓冲区(立刻将最后一桶数据写出到文件)
writer.Flush()
fmt.Println("写出完毕!")
}
2)便捷式写入
package main
import (
"fmt"
"os"
)
func main() {
data := "测试"
dataBytes := []byte(data)
err := os.WriteFile("D:/go_work/src/demo/1.json", dataBytes,0666)
if err !=nil{
fmt.Println(err)
return
}
fmt.Println("ok")
}
文件拷贝
1)判断文件是否存在
package main
import (
"fmt"
"os"
)
func main() {
fileInfo, err := os.Stat("D:/1go_work/src/demo/1.json")
if err != nil {
fmt.Println(err)
if os.IsNotExist(err) {
fmt.Println("文件不存在")
}
} else {
fmt.Println("文件存在", fileInfo)
}
}
2)文件简易拷贝
package main
import (
"fmt"
"os"
)
func main() {
bytes, err := os.ReadFile("D:/go_work/src/demo/1.json")
if err != nil {
fmt.Println(err)
if os.IsNotExist(err) {
fmt.Println("文件不存在")
}
} else {
err := os.WriteFile("D:/go_work/src/demo/2.json", bytes, 0666)
if err != nil {
fmt.Println(err)
}
fmt.Println("拷贝成功")
}
}
3)io.Copy(dstFile,srcFile)使用
package main
import (
"fmt"
"io"
"os"
)
func main() {
//打开拷贝源文件,注意模式为只读模式
srcFile, _ := os.OpenFile("D:/go_work/src/demo/1.json", os.O_RDONLY, 0666)
//打开要拷贝到的目标文件,注意模式:创建+写出
dstFile, _ := os.OpenFile("D:/go_work/src/demo/2.json", os.O_WRONLY|os.O_CREATE, 0666)
//执行源文件到目标文件的拷贝
written, err := io.Copy(dstFile, srcFile)
//判断执行结果
if err == nil {
fmt.Println("拷贝成功,字节数=", written)
} else {
fmt.Println("拷贝失败", err)
}
}
4)缓冲式拷贝
适合大文件,不用一次性存储在缓存中占用大量缓存,采用一通一桶分割缓冲存储
package main
import (
"bufio"
"fmt"
"io"
"os"
)
/*使用缓冲1K的缓冲区配合缓冲读写器进行图片拷贝*/
func main() {
//打开源文件
srcFile, _ := os.OpenFile("D:/go_work/src/demo/1.mp4", os.O_RDONLY, 0666)
//打开目标文件
dstFile, _ := os.OpenFile("D:/go_work/src/demo/2.mp4", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
//延时关闭他们
defer func() {
srcFile.Close()
dstFile.Close()
fmt.Println("文件全部关闭!")
}()
//创建源文件的缓冲读取器
reader := bufio.NewReader(srcFile)
//创建目标文件的写出器
writer := bufio.NewWriter(dstFile)
//创建小水桶(缓冲区)
buffer := make([]byte, 1024)
//一桶一桶地读入数据到水桶(缓冲区),直到io.EOF
for {
_, err := reader.Read(buffer)
if err != nil {
if err == io.EOF {
fmt.Println("源文件读取完毕!")
break
} else {
fmt.Println("读取源文件发生错误,err=", err)
return
}
} else {
//将每桶数据写出到目标文件
_, err := writer.Write(buffer)
if err != nil {
fmt.Println("写出错误,err=", err)
return
}
}
}
fmt.Println("拷贝完毕!")
}
版权声明
本文为[刘远山]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_39218464/article/details/124357256
边栏推荐
- Submit local warehouse and synchronize code cloud warehouse
- JVM class loading mechanism
- 587. Install fence / Sword finger offer II 014 Anagrams in strings
- 102. Sequence traversal of binary tree
- Halo open source project learning (II): entity classes and data tables
- Uniapp custom search box adaptation applet alignment capsule
- The method of changing a value in the array and a value in the object of wechat applet
- How to manually implement the mechanism of triggering garbage collection in node
- Gaode map search, drag and drop query address
- Client example analysis of easymodbustcp
猜你喜欢

Halo 开源项目学习(二):实体类与数据表

MySQL进阶之索引【分类,性能分析,使用,设计原则】

The ultimate experience, the audio and video technology behind the tiktok

MySQL进阶学习之SQL优化【插入,主键,排序,分组,分页,计数】

394. String decoding - auxiliary stack

2022 tea artist (primary) examination simulated 100 questions and simulated examination

440. The k-th small number of dictionary order (difficult) - dictionary tree - number node - byte skipping high-frequency question

Uniapp custom search box adaptation applet alignment capsule

1217_ Generating target files using scons

编译原理 求first集 follow集 select集预测分析表 判断符号串是否符合文法定义(有源码!!!)
随机推荐
440. 字典序的第K小数字(困难)-字典树-数节点-字节跳动高频题
Open source key component multi_ Button use, including test engineering
440. The k-th small number of dictionary order (difficult) - dictionary tree - number node - byte skipping high-frequency question
Listen for click events other than an element
C1小笔记【任务训练篇一】
Allowed latency and side output
Uniapp custom search box adaptation applet alignment capsule
Construction of functions in C language programming
402. Remove K digits - greedy
给 el-dialog 增加拖拽功能
2022 tea artist (primary) examination simulated 100 questions and simulated examination
Encapsulate a timestamp to date method on string prototype
Learning record of uni app dark horse yougou project (Part 2)
油猴网站地址
MySQL进阶学习之SQL优化【插入,主键,排序,分组,分页,计数】
Vite configure proxy proxy to solve cross domain
102. 二叉树的层序遍历
Kubernetes 服务发现 监控Endpoints
flink 学习(十二)Allowed Lateness和 Side Output
EasymodbusTCP之clientexample解析