当前位置:网站首页>Understand the reading, writing and creation of files in go language
Understand the reading, writing and creation of files in go language
2022-07-04 20:29:00 【1024 questions】
1. Opening and closing of files
1.1 os.open
1.2 os.OpenFile() Open file in specified mode
2. File reading
2.1 Read the data in the file by opening the file
2.2 Use bufio Read the whole line of the file
3. Write file operation
3.1 file.Write And file.WriteString
3.2 bufio.NewWriter
3.3 ioUtil Tool class
1. Opening and closing of files 1.1 os.openos.open Function can open a file call close() Method Close file
// Open file open, err := os.Open("./1.text")if err != nil {// Print exception information fmt.Println("open file err", err)}fmt.Println(" File acquisition completed ")// No exception occurred , Close file open.Close()
To prevent forgetting to close the file , Usually, the code to close the file is written in defer in
// Open file open, err := os.Open("./1.text")defer func() {if open != nil {// Close file open.Close()}}()if err != nil {// Print exception information fmt.Println("open file err", err)}fmt.Println(" File acquisition completed ")
1.2 os.OpenFile() Open file in specified mode func OpenFile(name string, flag int, perm FileMode) (*File, error) { ...}
among :
name: The name of the file to open flag: Open file mode . There are several modes :
os.O_WRONLY | Just write |
os.O_CREATE | create a file |
os.O_RDONLY | read-only |
os.O_RDWR | Reading and writing |
os.O_TRUNC | Empty |
os.O_APPEND | Additional |
perm: File permissions , An octal number .r( read )04,w( Write )02,x( perform )01.
2. File reading 2.1 Read the data in the file by opening the file// First you need to open a file open, err := os.Open("./1.text")defer func() {e := recover()if e != nil {fmt.Println(" An exception occurred when opening the file ", e)}}()if err != nil {// If there is any abnormality There's no need to go down Throw out panic(err)}// If there is no abnormality // establish Byte slice bytes := make([]byte, 1024)defer func() {e := recover()if e != nil {fmt.Println(" An exception occurred while reading the file ", e)}}()for {// Circle reading _, err := open.Read(bytes)if err != nil {panic(err)}// Print the results fmt.Println(string(bytes))}
2.2 Use bufio Read the whole line of the file bufio Is in file It encapsulates a layer of API , Support more functions
// Similarly, first open a file file, err := os.Open("./1.text")defer recover()if err != nil {panic(" An exception occurred while opening the file ")}// Encapsulated in the bufioreader := bufio.NewReader(file)defer recover()for {// Read the specified string and change to another line line, _, err := reader.ReadLine()if err != nil {if err == io.EOF {fmt.Println(" The file is read and written ")break}panic(" File reading exception ")}fmt.Println(string(line))}fmt.Println(" End of program running ")func main() {file, err := os.OpenFile("xx.txt", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)}
3. Write file operation Whether it is file reading or file writing You need to open the file first Do it again
3.1 file.Write And file.WriteString// So let's open the file O_RDWR read-write permission O_TRUNC Empty files 0 Start with octal 666 Express Current user Current group Other users Read and write permissions file, err := os.OpenFile("1.text", os.O_RDWR|os.O_TRUNC, 0666)if err != nil {fmt.Printf(" Exception in opening file %v", err)}defer file.Close()// return Bytes written write, err := file.Write([]byte(" Test file write \n"))file.WriteString(" Write the entire string at once ")if err != nil {fmt.Println(err)}fmt.Println(write)
3.2 bufio.NewWriter// Based on cache operation 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(" abnormal : Exception in opening file %v", e)}}()// Use bufio Based on cache operation io flow // Need to One io Interface package Writer Interface implementation class and file It's time to Method writer := bufio.NewWriter(file)writer.WriteString(" Write cache string contents 2")// You need to refresh the data in the cache to the hard disk writer.Flush()
3.3 ioUtil Tool class // Use tool class Open file , Write the file at one go err := ioutil.WriteFile("3.text", []byte(" Tool class writes content "), 0666)if err != nil {fmt.Println(" The program runs abnormally ", err)}
This is the article about understanding Go This is the article about reading, writing and creating files in the language , More about Go Language File read and write Please search the previous articles of SDN or continue to browse the relevant articles below. I hope you will support SDN more in the future !
边栏推荐
- Talking about cookies of client storage technology
- 太方便了,钉钉上就可完成代码发布审批啦!
- c# .net mvc 使用百度Ueditor富文本框上传文件(图片,视频等)
- Is it necessary to apply for code signing certificate for software client digital signature?
- What ppt writing skills does the classic "pyramid principle" teach us?
- 1500万员工轻松管理,云原生数据库GaussDB让HR办公更高效
- MySQL中的日期时间类型与格式化方式
- Six stones programming: about code, there are six triumphs
- C语言-入门-基础-语法-流程控制(七)
- 原来这才是 BGP 协议
猜你喜欢
Development and construction of DFI ecological NFT mobile mining system
Dark horse programmer - software testing - stage 08 2-linux and database-23-30-process port related, modify file permissions, obtain port number information, program and process related operations, Li
So this is the BGP agreement
FS8B711S14电动红酒开瓶器单片机IC方案开发专用集成IC
Process of manually encrypt the mass-producing firmware and programming ESP devices
What should we pay attention to when doing social media marketing? Here is the success secret of shopline sellers!
c# .net mvc 使用百度Ueditor富文本框上传文件(图片,视频等)
Application practice | Shuhai supply chain construction of data center based on Apache Doris
应用实践 | 蜀海供应链基于 Apache Doris 的数据中台建设
[Beijing Xunwei] i.mx6ull development board porting Debian file system
随机推荐
紫光展锐完成全球首个 5G R17 IoT NTN 卫星物联网上星实测
CANN算子:利用迭代器高效实现Tensor数据切割分块处理
更强的 JsonPath 兼容性及性能测试之2022版(Snack3,Fastjson2,jayway.jsonpath)
多表操作-内连接查询
被奉为经典的「金字塔原理」,教给我们哪些PPT写作技巧?
哈希(Hash)竞猜游戏系统开发功能分析及源码
PHP pseudo original API docking method
What financial products can you buy with a deposit of 100000 yuan?
Prometheus installation
Data set division
Huawei cloud store homepage banner resource bit application
Application practice | Shuhai supply chain construction of data center based on Apache Doris
In operation (i.e. included in) usage of SSRs filter
Why is the maximum speed the speed of light
What ppt writing skills does the classic "pyramid principle" teach us?
1009 product of polynomials (25 points) (PAT class a)
Optimization cases of complex factor calculation: deep imbalance, buying and selling pressure index, volatility calculation
Actual combat simulation │ JWT login authentication
原来这才是 BGP 协议
C # better operation mongodb database