扣丁书屋

把文件夹压缩成一个zip文件

1年以前  |  阅读数:92 次  |    

主要知识点:递归找文件和压缩库的使用

package main

import (
    "time"
    "fmt"
    "strings"
    "os"
    "archive/zip"
    "io/ioutil"
    "path/filepath"
    "io"
)

func main() {

    //oldFileName可以是文件或者目录
    oldFileName := "root.log"

    compressZip(oldFileName)
}

func compressZip(oldFileName string) string{

    fd, err := ioutil.ReadFile(oldFileName)

    if err != nil {
        fmt.Println("ReadFile ", oldFileName, "is error ", err)
        return ""
    }

    currentTime := time.Now()

    mSecond := fmt.Sprintf("%03d", currentTime.Nanosecond() / 1e6)

    zipFileName := strings.Split(oldFileName, ".")[0] + "_" + currentTime.Format("20060102150405") + mSecond + ".zip"

    fw, err := os.OpenFile(zipFileName, os.O_RDWR | os.O_CREATE | os.O_TRUNC, 400)

    if err != nil {
        fmt.Println("OpenFile ", zipFileName, "is error ", err)
        return ""
    }

    defer fw.Close()

    w := zip.NewWriter(fw)

    defer w.Close()

    f, err := w.Create(filepath.Base(oldFileName))

    if err != nil {
        fmt.Println("Create ", oldFileName, "is error ", err)
        return ""
    }

    _, err = f.Write(fd)

    if err != nil {
        fmt.Println("Write newFileName is error ", err)
        return ""
    }

    return zipFileName
}

相关文章: