Learn a little go src every day.
Today learned the simple use of the ZIP package, the implementation of the compression and decompression with the directory.
Wrote two methods, the implementation of compression, decompression.
Package Ziptestimport ("Archive/zip" "IO" "OS" "strings")//Compressed file//files file array, can be different dir file or folder//dest compressed file storage address Func Compress (Files []*os. File, dest String) error {D, _: = OS. Create (dest) Defer D.close () W: = Zip. Newwriter (d) defer w.close () for _, File: = Range Files {err: = Compress (File, "", W) if err! = Nil {return Err}}return nil}f UNC compress (file *os. File, prefix string, ZW *zip. Writer) Error {info, err: = file. Stat () if err! = Nil {return err}if info. Isdir () {prefix = prefix + "/" + info. Name () Fileinfos, err: = file. Readdir ( -1) if err! = Nil {return err}for _, fi: = Range Fileinfos {f, err: = OS. Open (file. Name () + "/" + FI. Name ()) if err! = Nil {return err}err = compress (f, prefix, ZW) if err! = Nil {return err}}} else {header, err: = Zip. Fileinfoheader (Info) header. Name = prefix + "/" + header. Nameif Err! = Nil {return err}writer, err: = ZW. CreateHeader (header) If err! = Nil {return err}_, err = io. Copy (writer, file) file. Close () if err! = Nil {return Err}}return nil}//decompression func decompress (ZipFile,Dest String) error {reader, err: = Zip. Openreader (ZipFile) if err! = Nil {return Err}defer reader. Close () for _, File: = Range reader. File {rc, err: = file. Open () if err! = Nil {return Err}defer RC. Close () FileName: = dest + file. Nameerr = OS. Mkdirall (Getdir (filename), 0755) if err! = Nil {return err}w, err: = OS. Create (filename) if err! = Nil {return Err}defer w.close () _, err = Io. Copy (W, RC) if err! = Nil {return err}w.close () RC. Close ()}return nil}func getdir (path String) string {return subString (path, 0, strings. LastIndex (Path, "/"))}func subString (str string, start, end int) string {rs: = []rune (str) Length: = Len (rs) if start < 0 || Start > Length {panic ("Start is wrong")}if End < Start | | End > Length {panic ("End is Wrong")}return string (Rs[start:end])}
Test code:
Package Ziptestimport ("OS" "Testing") Func testcompress (t *testing. T) {f1, err: = OS. Open ("/home/zzw/test_data/ziptest/gophercolor16x16.png") if err! = Nil {t.fatal (err)}defer F1. Close () F2, err: = OS. Open ("/home/zzw/test_data/ziptest/readme.notzip") if err! = Nil {t.fatal (err)}defer F2. Close () F3, Err: = OS. Open ("/home/zzw/test_data") if err! = Nil {t.fatal (err)}defer F3. Close () var files = []*os. FILE{F1, f2, f3}dest: = "/home/zzw/test_data/test.zip" err = Compress (files, dest) if err! = Nil {t.fatal (err)}}func Testdec Ompress (t *testing. T) {err: = Decompress ("/home/zzw/test_data/test.zip", "/home/zzw/test_data/de") if err! = Nil {t.fatal (err)}}
Golang zip compression, unzip (with catalog files)