当前位置:网站首页>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
边栏推荐
- Ring back to origin problem - byte jumping high frequency problem
- Ouvrir des contrats à terme, ouvrir des comptes en nuage ou faire confiance aux logiciels des sociétés à terme?
- Theory and practice of laser slam in dark blue College - Chapter 2 (odometer calibration)
- Element calculation distance and event object
- 2022年流动式起重机司机国家题库模拟考试平台操作
- 双指针进阶--leetcode题目--盛最多水的容器
- Special effects case collection: mouse planet small tail
- Anchor location - how to set the distance between the anchor and the top of the page. The anchor is located and offset from the top
- Sword finger offer 22 The penultimate node in the linked list - speed pointer
- Amount input box, used for recharge and withdrawal
猜你喜欢
Eigen learning summary
01 - get to know the advantages of sketch sketch
Why do some people say SCM is simple and I have to learn it so hard?
958. 二叉树的完全性检验
1217_使用SCons生成目标文件
Cloud native Virtualization: building edge computing instances based on kubevirt
470. 用 Rand7() 实现 Rand10()
Allowed latency and side output
SQL optimization for advanced learning of MySQL [insert, primary key, sort, group, page, count]
Client example analysis of easymodbustcp
随机推荐
Commonly used functions -- spineros:: and spineros::)
958. 二叉树的完全性检验
Ring back to origin problem - byte jumping high frequency problem
JS parsing and execution process
JS implementation private attribute
Eigen learning summary
41. The first missing positive number
Timestamp to formatted date
122. The best time to buy and sell stocks II - one-time traversal
JS forms the items with the same name in the array object into the same array according to the name
Qt error: /usr/bin/ld: cannot find -lGL: No such file or directory
2021 Great Wall Cup WP
MySQL advanced index [classification, performance analysis, use, design principles]
Gets the time range of the current week
vite配置proxy代理解决跨域
Compilation principle first set follow set select set prediction analysis table to judge whether the symbol string conforms to the grammar definition (with source code!!!)
Encapsulate a timestamp to date method on string prototype
干货 | 快速抽取缩略图是怎么练成的?
198. 打家劫舍-动态规划
31. Next arrangement