golang文件的压缩与解压
2018-01-08 本文已影响0人
吃猫的鱼0
判断是否是zip文件
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文件
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文件
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)
}