打包程序
package main
import (
"archive/zip"
"fmt"
"os"
)
func main() {
out, err := os.Create("test.zip")
if err != nil {
fmt.Println("Create error: ", err)
return
}
defer out.Close()
writer := zip.NewWriter(out)
var files = []struct {
Name, Body string
}{
{"1.txt", "test 1 file"},
{"2.txt", "test 2 file"},
}
for _, file := range files {
fileWriter, err := writer.Create(file.Name)
if err != nil {
if os.IsPermission(err) {
fmt.Println("权限不足: ", err)
return
}
fmt.Printf("Create file %s error: %s\n", file.Name, err.Error())
return
}
fileWriter.Write([]byte(file.Body))
}
if err := writer.Close(); err != nil{
fmt.Println("Close error: ", err)
}
}
解包程序
package main
import (
"fmt"
"archive/zip"
"os"
"path/filepath"
"io"
)
func main(){
const targetDir = "./"
zipReader, err := zip.OpenReader("test.zip")
if err != nil{
fmt.Println("OpenReader failed: ", err)
return
}
defer zipReader.Close()
for _, file := range zipReader.Reader.File{
zippedFile, err := file.Open()
if err != nil{
fmt.Println("Open error: ", err)
return
}
defer zippedFile.Close()
extractedFilePath := filepath.Join(targetDir, file.Name)
if file.FileInfo().IsDir(){
fmt.Println("正在创建目录: ", extractedFilePath)
os.MkdirAll(extractedFilePath, file.Mode())
}else{
fmt.Println("正在提取文件: ", file.Name)
outputFile, err := os.OpenFile(extractedFilePath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, file.Mode())
if err != nil{
fmt.Println(err)
return
}
defer outputFile.Close()
_, err = io.Copy(outputFile, zippedFile)
if err != nil{
fmt.Println("Err: ", err)
return
}
}
}
}
转载请注明原文地址:https://blackberry.8miu.com/read-34041.html