-
Notifications
You must be signed in to change notification settings - Fork 0
/
ZipUtil.go
144 lines (135 loc) · 2.52 KB
/
ZipUtil.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package go_log
import (
"archive/zip"
"io"
"os"
"strings"
)
// Compress
//
// @Description:压缩文件
// @param files 文件数组,可以是不同dir下的文件或者文件夹
// @param dest 压缩文件存放地址
// @return error
func Compress(files []*os.File, dest string) error {
d, _ := os.Create(dest)
defer d.Close()
w := zip.NewWriter(d)
defer w.Close()
for _, file := range files {
err := compress(file, "", w)
if err != nil {
return err
}
}
return nil
}
// compress
//
// @Description: 递归实现压缩
// @param file
// @param prefix
// @param zw
// @return error
func compress(file *os.File, prefix string, zw *zip.Writer) error {
info, err := file.Stat()
if err != nil {
return err
}
if info.IsDir() {
prefix = prefix + "/" + info.Name()
fileInfos, err := file.Readdir(-1)
if err != nil {
return err
}
for _, fi := range fileInfos {
f, err := os.Open(file.Name() + "/" + fi.Name())
if err != nil {
return err
}
err = compress(f, prefix, zw)
if err != nil {
return err
}
}
} else {
header, err := zip.FileInfoHeader(info)
header.Name = prefix + "/" + header.Name
if err != nil {
return err
}
writer, err := zw.CreateHeader(header)
if err != nil {
return err
}
_, err = io.Copy(writer, file)
_ = file.Close()
if err != nil {
return err
}
}
return nil
}
// DeCompress
//
// @Description: 解压
// @param zipFile 压缩文件存放地址
// @param dest 解压到目标路径
// @return error
func DeCompress(zipFile, dest string) error {
reader, err := zip.OpenReader(zipFile)
if err != nil {
return err
}
defer reader.Close()
for _, file := range reader.File {
rc, err := file.Open()
if err != nil {
return err
}
defer rc.Close()
filename := dest + file.Name
err = os.MkdirAll(getDir(filename), 0755)
if err != nil {
return err
}
w, err := os.Create(filename)
if err != nil {
return err
}
defer w.Close()
_, err = io.Copy(w, rc)
if err != nil {
return err
}
w.Close()
rc.Close()
}
return nil
}
// getDir
//
// @Description:
// @param path
// @return string
func getDir(path string) string {
return subString(path, 0, strings.LastIndex(path, "/"))
}
// subString
//
// @Description:
// @param str
// @param start
// @param end
// @return string
func subString(str string, start, end int) string {
rs := []rune(str)
length := len(rs)
if start < 0 || start > length {
panic("start is wrong")
}
if end < start || end > length {
panic("end is wrong")
}
return string(rs[start:end])
}