Go基础-压缩

摘要

  • gzip

gzip

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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package gzip

import (
"compress/gzip"
"errors"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"time"
"utils"
)

func fileToDecompress(gzfile, file string) string {
if file == "" {
file = gzfile
} else {
dir, fileName := filepath.Split(file)
if dir != "" {
err := os.MkdirAll(dir, 0755)
if err != nil {
log.Println(err)
return ""
}
}

if fileName == "" {
_, fileName = filepath.Split(gzfile)
}
file = filepath.Join(dir, fileName)
}
return strings.TrimSuffix(file, ".gz")
}

func fileToCompress(file, gzfile string) string {
if gzfile == "" {
gzfile = file
} else {
dir, fileName := filepath.Split(gzfile)
if dir != "" {
err := os.MkdirAll(dir, 0755)
if err != nil {
log.Println(err)
return ""
}
}

if fileName == "" {
_, fileName = filepath.Split(file)
}
gzfile = filepath.Join(dir, fileName)
}
if strings.ToLower(filepath.Ext(gzfile)) != ".gz" {
return gzfile + ".gz"
} else {
return gzfile
}
}

//压缩文件
//file 待压缩的文件 如 path/pkg.tar
//gzfile 压缩后的文件 如 path/pkg.tar.gz OR path/ OR 为空
func Compress(file, gzfile string) error {
if !utils.FileExists(file) {
return errors.New(`File "` + file + `" not exist.`)
}

gzfile = fileToCompress(file, gzfile)
if gzfile == "" {
return errors.New(`Can not determine file name to save.`)
}

gzfile = utils.UNCPath(gzfile)
file = utils.UNCPath(file)

in, err := os.Open(file)
defer in.Close()
if err != nil {
log.Println(err)
return err
}

out, err := os.Create(gzfile)
defer out.Close()
if err != nil {
log.Println(err)
return err
}

//zw, err := gzip.NewWriterLevel(out, gzip.DefaultCompression)
zw, err := gzip.NewWriterLevel(out, gzip.BestCompression)

if err != nil {
log.Println(err)
return err
}
// Setting the Header fields is optional.
zw.Name = filepath.Base(file)
zw.Comment = "NONE"
zw.ModTime = time.Now() //time.Date(1977, time.May, 25, 0, 0, 0, 0, time.UTC)

//10M per read
var buffer []byte = make([]byte, 10*1024*1024)
for {
size, err := in.Read(buffer)
if err != nil {
if size == 0 && err == io.EOF {
break
} else {
log.Println(err)
return err
}
}
buffer = buffer[0:size]
_, err = zw.Write(buffer)
if err != nil {
log.Println(err)
return err
}
}

if err := zw.Close(); err != nil {
log.Println(err)
return err
}
return nil
}

//解压缩文件
//gzfile 待解压缩的文件 如 path/pkg.tar.gz
//file 解压缩后的文件 如 path/pkg.tar OR path/ OR 为空
func Decompress(gzfile, file string) error {
if !utils.FileExists(gzfile) {
return errors.New(`File "` + gzfile + `" not exist.`)
}

if strings.ToLower(filepath.Ext(gzfile)) != ".gz" {
return errors.New(`"` + gzfile + `" is not gzip file.`)
}

file = fileToDecompress(gzfile, file)
if gzfile == "" {
return errors.New(`Can not determine file name to save.`)
}
file = utils.UNCPath(file)
gzfile = utils.UNCPath(gzfile)

in, err := os.Open(gzfile)
if err != nil {
log.Println(err)
return err
}

zr, err := gzip.NewReader(in)
if err != nil {
log.Println(err)
return err
}

fmt.Printf("Name: %s\nComment: %s\nModTime: %s\n\n", zr.Name, zr.Comment, zr.ModTime.UTC())

out, err := os.Create(file)
if err != nil {
log.Println(err)
return err
}

if _, err := io.Copy(out, zr); err != nil {
log.Println(err)
return err
}

if err := zr.Close(); err != nil {
log.Println(err)
return err
}
return nil
}

解压tar.gz

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

func unCompress(srcFilePath string, destDirPath string) error {
os.Mkdir(destDirPath, os.ModePerm)

fr, err := os.Open(srcFilePath)
if err != nil {
return err
}
defer fr.Close()

gr, err := gzip.NewReader(fr)
if err != nil {
return err
}
defer gr.Close()

tr := tar.NewReader(gr)

for {
hdr, err := tr.Next()
if err == io.EOF {
break
}

if hdr.Typeflag != tar.TypeDir {
// fmt.Println(hdr.Name)
os.MkdirAll(destDirPath+"/"+path.Dir(hdr.Name), os.ModePerm)

fw, _ := os.OpenFile(destDirPath+"/"+hdr.Name, os.O_CREATE|os.O_WRONLY, os.FileMode(hdr.Mode))

if err != nil {
return err
}
_, err = io.Copy(fw, tr)
if err != nil {
return err
}
} else {
// fmt.Println(hdr.Name)
os.MkdirAll(destDirPath+"/"+hdr.Name, os.ModePerm)
}
}
return nil
}

zip

判断是否zip文件

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
package main

import (
"bytes"
"fmt"
"os"
)

func isZip(zipPath string) bool {
f, err := os.Open(zipPath)
if err != nil {
return false
}
defer f.Close()

buf := make([]byte, 4)
if n, err := f.Read(buf); err != nil || n < 4 {
return false
}

return bytes.Equal(buf, []byte("PK\x03\x04"))
}

func main() {
result := isZip("1.zip")
fmt.Println(result)
}

解压zip

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
package main

import (
"archive/zip"
"bytes"
"fmt"
"io"
"os"
"path/filepath"
)

func unzip(archive, target string) error {
reader, err := zip.OpenReader(archive)
if err != nil {
return err
}

if err := os.MkdirAll(target, 0755); err != nil {
return err
}

for _, file := range reader.File {
path := filepath.Join(target, file.Name)
if file.FileInfo().IsDir() {
os.MkdirAll(path, file.Mode())
continue
}

fileReader, err := file.Open()
if err != nil {
return err
}
defer fileReader.Close()

targetFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())
if err != nil {
return err
}
defer targetFile.Close()

if _, err := io.Copy(targetFile, fileReader); err != nil {
return err
}
}

return nil
}

func main() {
result := isZip("1.zip")
fmt.Println(result)
unzip("1.zip", "./")
}

压缩zip

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
package main

import (
"archive/zip"
"bytes"
"log"
"os"
)

func main() {
buf := new(bytes.Buffer)

w := zip.NewWriter(buf)

var files = []struct {
Name, Body string
}{
{"1.txt", "first"},
{"2.txt", "second"},
{"3.txt", "third"},
}
for _, file := range files {
f, err := w.Create(file.Name)
if err != nil {
log.Fatal(err)
}
_, err = f.Write([]byte(file.Body))
if err != nil {
log.Fatal(err)
}
}

err := w.Close()
if err != nil {
log.Fatal(err)
}

f, err := os.OpenFile("file.zip", os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
log.Fatal(err)
}
buf.WriteTo(f)
}