1. 程式人生 > >golang 創建壓縮文件

golang 創建壓縮文件

路徑 替換 filename flat imp () 保存 生成 println

import ( "os" "archive/zip" "io" "fmt" "strings" ) // ZipFiles compresses one or many files into a single zip archive file. //壓縮多個文件到一個文件裏面 // Param 1: 輸出的zip文件的名字 // Param 2: 需要添加到zip文件裏面的文件 //Param 3: 由於file是絕對路徑,打包後可能不是想要的目錄,oldform就是filename中需要被替換的掉的路徑 //Param 4: 要替換成的路徑 func ZipFiles(filename string, files []string, oldform, newform string) error { newZipFile, err := os.Create(filename) if err != nil { return err } defer newZipFile.Close() zipWriter := zip.NewWriter(newZipFile) defer zipWriter.Close() // 把files添加到zip中 for _, file := range files { zipfile, err := os.Open(file) if err != nil { return err } defer zipfile.Close() // 獲取file的基礎信息 info, err := zipfile.Stat() if err != nil { return err } header, err := zip.FileInfoHeader(info) if err != nil { return err } //使用上面的FileInforHeader() 就可以把文件保存的路徑替換成我們自己想要的了,如下面 header.Name = strings.Replace(file, oldform, newform, -1) // 優化壓縮 // 更多參考see http://golang.org/pkg/archive/zip/#pkg-constants header.Method = zip.Deflate writer, err := zipWriter.CreateHeader(header) if err != nil { return err } if _, err = io.Copy(writer, zipfile); err != nil { return err } } return nil

使用方法 一

func main() {
    fileList := []string{
        "/Users/Jack/Downloads/QQreceiver/72bian_log/anal.txt",
        "/Users/Jack/Downloads/QQreceiver/72bian_log/config.json",
        "/Users/Jack/Downloads/QQreceiver/72bian_log/xzwx_client/md5.txt",
    }
    //保留原來文件的結構
    err := ZipFiles("/Users/Jack/Downloads/QQreceiver/test.zip", fileList, "","")
    if err != nil {
        fmt.Println(err)
    }
}

// 執行之後

//在對應目錄下生成了我們定義的zip文件
?  QQreceiver#  ls test.zip
test.zip
?  QQreceiver#  pwd
/Users/Jack/Downloads/QQreceiver
//解壓test.zip
?  QQreceiver# ls
Users    test.zip
?  QQreceiver# ls -R Users
Jack

Users/Jack:
Downloads

Users/Jack/Downloads:
QQreceiver

Users/Jack/Downloads/QQreceiver:
72bian_log

Users/Jack/Downloads/QQreceiver/72bian_log:
anal.txt    config.json xzwx_client

Users/Jack/Downloads/QQreceiver/72bian_log/xzwx_client:
md5.txt
//可以看到test打包的是文件的絕對路徑,如果這個test.zip是我們要更新的程序的目錄,這樣肯定是不能用的

使用方法 二:
替換成我們想要的結構

func main() {
    fileList := []string{
        "/Users/Jack/Downloads/QQreceiver/72bian_log/anal.txt",
        "/Users/Jack/Downloads/QQreceiver/72bian_log/config.json",
        "/Users/Jack/Downloads/QQreceiver/72bian_log/xzwx_client/md5.txt",
    }
    //比如線上的程序的目錄為game ,"/Users/Jack/Downloads/QQreceiver/72bian_log/"下面的文件為我們線game下的程序文件內容
    err := ZipFiles("/Users/Jack/Downloads/QQreceiver/test.zip", fileList, "/Users/Jack/Downloads/QQreceiver/72bian_log","game/")
    if err != nil {
        fmt.Println(err)
    }
}

執行之後

//在對應目錄下生同樣生成了我們定義的zip文件
?  QQreceiver#  ls test.zip
test.zip
?  QQreceiver#  pwd
/Users/Jack/Downloads/QQreceiver
//解壓test.zip
?  QQreceiver# ls
game     test.zip
?  QQreceiver# ls -R game
anal.txt    config.json xzwx_client

game/xzwx_client:
md5.txt
//上面正好是我們需要的目錄

golang 創建壓縮文件