当前位置:网站首页>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 !
边栏推荐
- 记一次 .NET 某工控数据采集平台 线程数 爆高分析
- Aiming at the "amnesia" of deep learning, scientists proposed that based on similarity weighted interleaved learning, they can board PNAS
- c# .net mvc 使用百度Ueditor富文本框上传文件(图片,视频等)
- 实践示例理解js强缓存协商缓存
- Neural network IOT platform construction (IOT platform construction practical tutorial)
- [ismb2022 tutorial] the picture shows the precision medicine of learning. Marinka zitnik, Harvard University, keynote speaker, with 87 ppt
- Ziguang zhanrui completed the first 5g R17 IOT NTN satellite on the Internet of things in the world
- 2022 version of stronger jsonpath compatibility and performance test (snack3, fastjson2, jayway.jsonpath)
- TCP waves twice, have you seen it? What about four handshakes?
- Cbcgpprogressdlg progress bar used by BCG
猜你喜欢
NLP, vision, chip What is the development direction of AI? Release of the outlook report of Qingyuan Association [download attached]
Process of manually encrypt the mass-producing firmware and programming ESP devices
HMM hidden Markov model and code implementation
Dynamic memory management
QT writing the Internet of things management platform 38- multiple database support
Abc229 summary (connected component count of the longest continuous character graph in the interval)
【历史上的今天】7 月 4 日:第一本电子书问世;磁条卡的发明者出生;掌上电脑先驱诞生
Siemens HMI download prompts lack of panel image solution
关于联邦学习和激励的相关概念(1)
Selected review | machine learning technology for Cataract Classification / classification
随机推荐
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
Template_ Judging prime_ Square root / six prime method
[today in history] July 4: the first e-book came out; The inventor of magnetic stripe card was born; Palm computer pioneer was born
Kotlin classes and objects
PHP pseudo original API docking method
长城证券开户安全吗 股票开户流程网上开户
Talking about cookies of client storage technology
为什么最大速度是光速
Development and construction of DFI ecological NFT mobile mining system
应用实践 | 蜀海供应链基于 Apache Doris 的数据中台建设
Optimize if code with policy mode [policy mode]
C server log module
QT writing the Internet of things management platform 38- multiple database support
What is the application technology of neural network and Internet of things
实战模拟│JWT 登录认证
做社交媒体营销应该注意些什么?Shopline卖家的成功秘笈在这里!
Key rendering paths for performance optimization
[QNX Hypervisor 2.2用户手册]6.3.1 工厂页和控制页
Is it safe for Great Wall Securities to open an account? Stock account opening process online account opening
What does the neural network Internet of things mean? Popular explanation