当前位置:网站首页>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
边栏推荐
- Operation of 2022 mobile crane driver national question bank simulation examination platform
- 常用SQL语句总结
- Compare the performance of query based on the number of paging data that meet the query conditions
- 239. 滑动窗口最大值(困难)-单向队列、大顶堆-字节跳动高频题
- 练习:求偶数和、阈值分割和求差( list 对象的两个基础小题)
- On the problem of V-IF display and hiding
- 01 - get to know the advantages of sketch sketch
- Summary of common SQL statements
- MySQL advanced index [classification, performance analysis, use, design principles]
- 一些问题一些问题一些问题一些问题
猜你喜欢
958. 二叉树的完全性检验
Allowed latency and side output
2021 Great Wall Cup WP
Compare the performance of query based on the number of paging data that meet the query conditions
1217_使用SCons生成目标文件
双闭环直流调速系统matlab/simulink仿真
SQL optimization for advanced learning of MySQL [insert, primary key, sort, group, page, count]
Comparison between xtask and kotlin coroutine
编译原理 求first集 follow集 select集预测分析表 判断符号串是否符合文法定义(有源码!!!)
Halo open source project learning (II): entity classes and data tables
随机推荐
2022 judgment questions and answers for operation of refrigeration and air conditioning equipment
干货 | 快速抽取缩略图是怎么练成的?
Halo 开源项目学习(二):实体类与数据表
一些问题一些问题一些问题一些问题
Ring back to origin problem - byte jumping high frequency problem
Future 用法详解
Leak detection and vacancy filling (VII)
Dry goods | how to extract thumbnails quickly?
1217_使用SCons生成目标文件
Utilisation de la liste - Ajouter, supprimer et modifier la requête
In ancient Egypt and Greece, what base system was used in mathematics
关于gcc输出typeid完整名的方法
198. 打家劫舍-动态规划
2022 Shanghai safety officer C certificate operation certificate examination question bank and simulation examination
Gaode map search, drag and drop query address
索引:手把手教你索引从零基础到精通使用
极致体验,揭晓抖音背后的音视频技术
STM32 entry development board choose wildfire or punctual atom?
剑指 Offer 22. 链表中倒数第k个节点-快慢指针
Write a regular