当前位置:网站首页>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
边栏推荐
- Submit local warehouse and synchronize code cloud warehouse
- Cloud native Virtualization: building edge computing instances based on kubevirt
- 92. 反转链表 II-字节跳动高频题
- Land cover / use data product download
- C language implements memcpy, memset, strcpy, strncpy, StrCmp, strncmp and strlen
- Arithmetic expression
- 云原生虚拟化:基于 Kubevirt 构建边缘计算实例
- 干货 | 快速抽取缩略图是怎么练成的?
- 587. Install fence / Sword finger offer II 014 Anagrams in strings
- In JS, t, = > Analysis of
猜你喜欢
102. Sequence traversal of binary tree
Open source key component multi_ Button use, including test engineering
JS get link? The following parameter name or value, according to the URL? Judge the parameters after
394. String decoding - auxiliary stack
uni-app黑马优购项目学习记录(下)
2022年上海市安全员C证操作证考试题库及模拟考试
92. Reverse linked list II byte skipping high frequency question
2022江西储能技术展会,中国电池展,动力电池展,燃料电池展
SQL optimization for advanced learning of MySQL [insert, primary key, sort, group, page, count]
超分之TDAN
随机推荐
超分之TDAN
Qt error: /usr/bin/ld: cannot find -lGL: No such file or directory
470. Rand10() is implemented with rand7()
剑指 Offer 22. 链表中倒数第k个节点-快慢指针
41. The first missing positive number
Leak detection and vacancy filling (6)
[二叉数] 二叉树的最大深度+N叉树的最大深度
402. 移掉 K 位数字-贪心
209. Minimum length subarray - sliding window
386. 字典序排数(中等)-迭代-全排列
Summary of floating point double precision, single precision and half precision knowledge
flink 学习(十二)Allowed Lateness和 Side Output
C1 notes [task training part 2]
Theory and practice of laser slam in dark blue College - Chapter 2 (odometer calibration)
Read software engineering at Google (15)
SystemVerilog (VI) - variable
Operation of 2022 mobile crane driver national question bank simulation examination platform
Ring back to origin problem - byte jumping high frequency problem
Double pointer advanced -- leetcode title -- container with the most water
Exercise: even sum, threshold segmentation and difference (two basic questions of list object)