当前位置:网站首页>Go file operation
Go file operation
2022-04-23 17:52:00 【Liu Yuanshan】
Catalog

File read and write
File read operation
1) Open and close files
Easy way to open a file , File operations , Close in one second
package main
import (
"fmt"
"os"
"time"
)
func main() {
file, err := os.Open("D:/go_work/src/demo/1.json")
if err == nil {
fmt.Println(" File opened successfully ")
} else {
fmt.Println(" File opening failure ,err=", err)
return
}
defer func() {
file.Close()
fmt.Println(" The file is closed ")
}()
fmt.Println(" File operations ", file)
time.Sleep(1 * time.Second)
}
2) Buffered file read in
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func main() {
// Open the file in read-only mode (0666 It means that everyone has read and write permission )
file, err := os.OpenFile("D:/go_work/src/demo/1.json", os.O_RDONLY, 0666)
// Judge whether the file is opened successfully
if err == nil {
fmt.Println(" File opened successfully ")
} else {
fmt.Println(" File opening failure ,err=", err)
return
}
// Time delay ( Before the function returns ) Close file - Before the function returns, it will execute defer Guided statement
defer func() {
file.Close()
fmt.Println(" The file is closed ")
}()
// Create a buffer reader for this file
reader := bufio.NewReader(file)
// Loop in data
for {
// Read in one line at a time
str, err := reader.ReadString('\n')
// Judge whether the reading is successful
if err == nil {
// Print the read string
fmt.Println(str)
} else {
if err == io.EOF {
// End of file , Jump out of the read loop
fmt.Println(" End of file !")
break
} else {
// There are other exceptions , Print the exception and end the program
fmt.Println(" Read failed ,err=", err)
return
}
}
}
fmt.Println(" File read complete !")
}
3) Easy to read files
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(" Read failed ,err=", err)
}
}
File write operation
1) Buffered write
package main
import (
"bufio"
"fmt"
"os"
)
/* With 【 gen - Write - Additional 】 or 【 gen - Write - Cover 】 Open a file in this way , Write out a few lines of data in buffer , Drain the buffer and exit ;*/
func main() {
// Open the specified file , Pattern : Create... If it doesn't exist + Just write + Additional , The permissions of the generated file are -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 there is any abnormality, print directly and exit
if err != nil {
fmt.Println(" File opening failure ,err=", err)
return
}
// Delay closing file
defer func() {
file.Close()
fmt.Println(" The file is closed ")
}()
// Write out the file buffer created by
writer := bufio.NewWriter(file)
// Write some data in batches
writer.WriteString(" test \n")
// Drain the buffer ( Write out the last bucket of data to the file immediately )
writer.Flush()
fmt.Println(" Write it out !")
}
2) Convenient write
package main
import (
"fmt"
"os"
)
func main() {
data := " test "
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")
}
A copy of a document
1) Judge whether the file exists
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(" file does not exist ")
}
} else {
fmt.Println(" File exists ", fileInfo)
}
}
2) Easy copy of files
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(" file does not exist ")
}
} else {
err := os.WriteFile("D:/go_work/src/demo/2.json", bytes, 0666)
if err != nil {
fmt.Println(err)
}
fmt.Println(" Success copy ")
}
}
3)io.Copy(dstFile,srcFile) Use
package main
import (
"fmt"
"io"
"os"
)
func main() {
// Open the copy source file , Note that the mode is read-only
srcFile, _ := os.OpenFile("D:/go_work/src/demo/1.json", os.O_RDONLY, 0666)
// Open the target file you want to copy to , Pay attention to the mode : establish + Write
dstFile, _ := os.OpenFile("D:/go_work/src/demo/2.json", os.O_WRONLY|os.O_CREATE, 0666)
// Execute the copy from source file to target file
written, err := io.Copy(dstFile, srcFile)
// Judge the execution result
if err == nil {
fmt.Println(" Success copy , Number of bytes =", written)
} else {
fmt.Println(" Copy failure ", err)
}
}
4) Buffered copy
Suitable for big documents , It doesn't need to be stored in the cache at one time, which takes up a lot of cache , Adopt one pass and one bucket split buffer storage
package main
import (
"bufio"
"fmt"
"io"
"os"
)
/* Use buffer 1K The buffer of is used to copy pictures with the buffer reader */
func main() {
// open the source file
srcFile, _ := os.OpenFile("D:/go_work/src/demo/1.mp4", os.O_RDONLY, 0666)
// Open the target file
dstFile, _ := os.OpenFile("D:/go_work/src/demo/2.mp4", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
// Delay closing them
defer func() {
srcFile.Close()
dstFile.Close()
fmt.Println(" All files are closed !")
}()
// Create a buffer reader for the source file
reader := bufio.NewReader(srcFile)
// The writer that creates the target file
writer := bufio.NewWriter(dstFile)
// Create a small bucket ( buffer )
buffer := make([]byte, 1024)
// Read data bucket by bucket into the bucket ( buffer ), until io.EOF
for {
_, err := reader.Read(buffer)
if err != nil {
if err == io.EOF {
fmt.Println(" Finished reading source file !")
break
} else {
fmt.Println(" Error reading source file ,err=", err)
return
}
} else {
// Write out a barrel of data to the target file
_, err := writer.Write(buffer)
if err != nil {
fmt.Println(" Write mistakes ,err=", err)
return
}
}
}
fmt.Println(" Copy complete !")
}
版权声明
本文为[Liu Yuanshan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231751425092.html
边栏推荐
- Read software engineering at Google (15)
- 394. 字符串解码-辅助栈
- C1 notes [task training part 2]
- Qt 修改UI没有生效
- Add drag and drop function to El dialog
- 编译原理 求first集 follow集 select集预测分析表 判断符号串是否符合文法定义(有源码!!!)
- Summary of common server error codes
- [binary number] maximum depth of binary tree + maximum depth of n-ary tree
- [二叉数] 二叉树的最大深度+N叉树的最大深度
- 剑指 Offer 22. 链表中倒数第k个节点-快慢指针
猜你喜欢

394. 字符串解码-辅助栈

Gets the time range of the current week

Remember using Ali Font Icon Library for the first time

In JS, t, = > Analysis of

2022 Shanghai safety officer C certificate operation certificate examination question bank and simulation examination

Dry goods | how to extract thumbnails quickly?

Qt 修改UI没有生效

Tdan over half

EasymodbusTCP之clientexample解析
![Click Cancel to return to the previous page and modify the parameter value of the previous page, let pages = getcurrentpages() let prevpage = pages [pages. Length - 2] / / the data of the previous pag](/img/ed/4d61ce34f830209f5adbddf9165676.png)
Click Cancel to return to the previous page and modify the parameter value of the previous page, let pages = getcurrentpages() let prevpage = pages [pages. Length - 2] / / the data of the previous pag
随机推荐
JS implementation private attribute
Learning record of uni app dark horse yougou project (Part 2)
402. Remove K digits - greedy
1217_ Generating target files using scons
uni-app黑马优购项目学习记录(下)
Open source key component multi_ Button use, including test engineering
Where is the configuration file of tidb server?
198. 打家劫舍-动态规划
vite配置proxy代理解决跨域
Flask项目的部署详解
Open futures, open an account, cloud security or trust the software of futures companies?
Summary of common SQL statements
Tell the truth of TS
958. 二叉树的完全性检验
双指针进阶--leetcode题目--盛最多水的容器
JS parsing and execution process
Client example analysis of easymodbustcp
Leak detection and vacancy filling (VIII)
587. 安装栅栏 / 剑指 Offer II 014. 字符串中的变位词
开源按键组件Multi_Button的使用,含测试工程