-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
88 lines (78 loc) · 1.85 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
88
package iohelper
import (
"bufio"
"fmt"
"os"
)
// ReadStringFromFile returns content of the file in the specified path as string
func ReadStringFromFile(path string) (string, error) {
bytes, err := ReadBytesFromFile(path)
if err != nil {
return "", err
}
return string(bytes), nil
}
// ReadBytesFromFile returns content of the file in the specified path as bytes
func ReadBytesFromFile(path string) ([]byte, error) {
if path == "" {
return nil, fmt.Errorf("path cannot be empty")
}
if !IsFileExist(path) {
return nil, fmt.Errorf("file [%s] does not exist", path)
}
file, errFile := os.ReadFile(path)
if errFile != nil {
return nil, errFile
}
return file, nil
}
func ReadFirstLineFromFile(path string) (string, error) {
bytes, err := ReadFirstLineBytesFromFile(path)
if err != nil {
return "", err
}
return string(bytes), nil
}
func ReadFirstLineBytesFromFile(path string) ([]byte, error) {
if path == "" {
return nil, fmt.Errorf("path cannot be empty")
}
if !IsFileExist(path) {
return nil, fmt.Errorf("file [%s] does not exist", path)
}
file, errFile := os.Open(path)
if errFile != nil {
return nil, errFile
}
defer file.Close()
scanner := bufio.NewScanner(file)
if scanner.Scan() {
return scanner.Bytes(), nil
}
return nil, nil
}
// IsFileExist return true if a file exist in the specified path
func IsFileExist(path string) bool {
info, err := os.Stat(path)
if os.IsNotExist(err) {
return false
}
return info.Mode().IsRegular()
}
// IsDirectoryExist return true if a file exist in the specified path
func IsDirectoryExist(path string) bool {
info, err := os.Stat(path)
if os.IsNotExist(err) {
return false
}
return info.Mode().IsDir()
}
func CreateDirectory(path string) error {
if path == "" {
return fmt.Errorf("path cannot be empty")
}
if IsDirectoryExist(path) {
return nil
}
return os.MkdirAll(path, 0755)
}