-
Notifications
You must be signed in to change notification settings - Fork 3
/
operationRead.go
72 lines (61 loc) · 1.53 KB
/
operationRead.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
package fileKit
import (
"bufio"
"bytes"
"github.com/gogf/gf/v2/os/gfile"
"github.com/richelieu-yang/chimera/v2/src/core/strKit"
"os"
)
var (
ReadLines func(file string, callback func(line string) error) error = gfile.ReadLines
ReadLinesBytes func(file string, callback func(bytes []byte) error) error = gfile.ReadLinesBytes
)
// ReadFile 读取文件的数据.
/*
PS:
(1) ioutil.ReadFile() 比 ioutil.ReadAll() 性能好,特别是大文件;
(2) 编码必须为"UTF-8"!!!
@param path 文件的路径(不能是目录的路径)
*/
func ReadFile(filePath string) ([]byte, error) {
if err := AssertExistAndIsFile(filePath); err != nil {
return nil, err
}
return os.ReadFile(filePath)
}
func ReadFileString(filePath string) (string, error) {
if err := AssertExistAndIsFile(filePath); err != nil {
return "", err
}
data, err := os.ReadFile(filePath)
return string(data), err
}
// ReadLuaFile 按行读取 .lua文件 的内容.
/*
@param path .lua文件的路径
*/
func ReadLuaFile(path string) (string, error) {
file, err := os.Open(path)
defer file.Close()
if err != nil {
return "", err
}
var buffer = bytes.Buffer{}
scan := bufio.NewScanner(file)
for scan.Scan() {
line := scan.Text()
line = strKit.TrimSpace(line)
// 忽略"空行"和"注释行"
if strKit.IsEmpty(line) || strKit.StartWith(line, "--") {
continue
}
// 加个空格
buffer.WriteString(line + " ")
//line := scan.Bytes()
//buffer.Write(line)
}
if err := scan.Err(); err != nil {
return "", err
}
return buffer.String(), nil
}