当前位置:网站首页>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
边栏推荐
- 2021 Great Wall Cup WP
- Operation of 2022 mobile crane driver national question bank simulation examination platform
- Halo open source project learning (II): entity classes and data tables
- Why do some people say SCM is simple and I have to learn it so hard?
- Halo 开源项目学习(二):实体类与数据表
- Tdan over half
- Kubernetes service discovery monitoring endpoints
- Halo open source project learning (II): entity classes and data tables
- Welcome to the markdown editor
- SystemVerilog(六)-变量
猜你喜欢
flink 学习(十二)Allowed Lateness和 Side Output
2022 Shanghai safety officer C certificate operation certificate examination question bank and simulation examination
uni-app黑马优购项目学习记录(下)
Error in created hook: "referenceerror:" promise "undefined“
Gets the time range of the current week
102. Sequence traversal of binary tree
索引:手把手教你索引从零基础到精通使用
Gaode map search, drag and drop query address
Chrome浏览器的跨域设置----包含新老版本两种设置
Why do some people say SCM is simple and I have to learn it so hard?
随机推荐
Oil monkey website address
[二叉数] 二叉树的最大深度+N叉树的最大深度
flink 学习(十二)Allowed Lateness和 Side Output
STM32 entry development board choose wildfire or punctual atom?
Timestamp to formatted date
470. 用 Rand7() 实现 Rand10()
Summary of common SQL statements
Read software engineering at Google (15)
Hcip fifth experiment
2022制冷与空调设备运行操作判断题及答案
JVM class loading mechanism
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
Amount input box, used for recharge and withdrawal
Qt error: /usr/bin/ld: cannot find -lGL: No such file or directory
Open futures, open an account, cloud security or trust the software of futures companies?
Add animation to the picture under V-for timing
Listen for click events other than an element
Detailed deployment of flask project
C1小笔记【任务训练篇一】
Halo 开源项目学习(二):实体类与数据表