-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.go
87 lines (75 loc) · 1.89 KB
/
file.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package golibrary
import (
"bufio"
"gopkg.in/yaml.v3"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
// ReadFile 读取文件内容,返回bytes
func ReadFile(filePath string) ([]byte, error) {
content, err := ioutil.ReadFile(filePath)
if err != nil {
return nil, err
}
return content, nil
}
// WriteFile 将bytes写入目标文件
func WriteFile(filePath string, content []byte) error {
return os.WriteFile(filePath, content, 0644)
}
// WriteFileString 将string写入目标文件
func WriteFileString(filePath string, content string) error {
contentBytes := []byte(content)
return os.WriteFile(filePath, contentBytes, 0644)
}
// ReadFileString 读取文件内容,返回string
func ReadFileString(filePath string) (string, error) {
content, err := ReadFile(filePath)
if err != nil {
return "", err
}
return string(content), nil
}
// ParseYamlToStruct 将yaml文件解析成结构体
func ParseYamlToStruct(yamlPath string, s interface{}) error {
data, err := ReadFile(yamlPath)
if err != nil {
return err
}
err = yaml.Unmarshal(data, s)
if err != nil {
return err
}
return nil
}
// WalkDir 获取指定目录下的所有文件
func WalkDir(folderPath string) ([]string, error) {
var files []string
err := filepath.Walk(folderPath, func(path string, info os.FileInfo, err error) error {
if !info.IsDir() {
files = append(files, strings.ReplaceAll(path, "\\", "/"))
}
return nil
})
return files, err
}
// ReadFileLines 读取文件,每行分割, https://www.golangprograms.com/golang-read-file-line-by-line-to-string.html
func ReadFileLines(filePath string) ([]string, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
var lines []string
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
err = file.Close()
if err != nil {
return nil, err
}
return lines, nil
}