使用golang对文件进行zip打包和解包

    科技2024-10-20  25

    打包程序

    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{ // 如果文件在目录中间,那么file.Name也会包含目录的 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 } } } }
    Processed: 0.012, SQL: 8