PHP
·
发表于 5年以前
·
阅读量:8398
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
}