forked from pibigstar/go-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathread_file.go
75 lines (66 loc) · 1.33 KB
/
read_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
package file
import (
"bufio"
"crypto/sha1"
"encoding/hex"
"io"
"io/ioutil"
"os"
)
// 读取文件
// 使用 io.Copy
// 推荐
func Copy(path string) (fileMd5 string, err error) {
f, err := os.Open(path)
if err != nil {
return fileMd5, err
}
defer f.Close()
md5hash := sha1.New()
if _, err := io.Copy(md5hash, f); err != nil {
return fileMd5, err
}
fileMd5 = hex.EncodeToString(md5hash.Sum(nil))
return fileMd5, nil
}
// 使用ioutil.ReadAll
// 文件不能过大,不然会卡死
func ReadAll(path string) (fileMD5 string, err error) {
f, err := os.Open(path)
if err != nil {
return fileMD5, err
}
defer f.Close()
body, err := ioutil.ReadAll(f)
if err != nil {
return fileMD5, err
}
hash := sha1.New()
hash.Write(body)
fileMD5 = hex.EncodeToString(hash.Sum(nil))
return fileMD5, nil
}
// 使用 bufio.NewReader
func ReadBuf(path string) (fileMD5 string, err error) {
f, err := os.Open(path)
if err != nil {
return fileMD5, err
}
defer f.Close()
buf := make([]byte, 1024)
reader := bufio.NewReader(f)
md5hash := sha1.New()
for {
n, err := reader.Read(buf)
if err != nil { // 遇到任何错误立即返回,并忽略 EOF 错误信息
if err == io.EOF {
goto stop
}
return fileMD5, err
}
md5hash.Write(buf[:n])
}
stop:
fileMD5 = hex.EncodeToString(md5hash.Sum(nil))
return fileMD5, nil
}