1.读取写入tar文件
package main import ( "archive/tar" "fmt" "os" "bufio" "io" ) func readFile(path string) string{ var content string = "" file,err := os.Open(path) if err != nil{ fmt.Printf("%v",err) return "" } defer file.Close() inputReader := bufio.NewReader(file) for{ inputString,err := inputReader.ReadString('\n') content += inputString if err == io.EOF{ break } } return content } func tarPackage(tarFileName string,tarFileList []string,rootPath string){ fw,err := os.Create(rootPath+"/"+tarFileName) if err != nil{ fmt.Printf("%v",err) return } defer fw.Close() tw := tar.NewWriter(fw) defer tw.Close() for _,fileItem := range tarFileList{ body := readFile(rootPath+"/"+fileItem) hdr := &tar.Header{ Name:fileItem, Mode:0600, Size:int64(len(body)), } if err := tw.WriteHeader(hdr);err != nil{ fmt.Printf("%v",err) return } if _,err := tw.Write([]byte(body));err != nil{ fmt.Printf("%v",err) return } } fmt.Println("done!") } func tarReader(tarFileName string){ fw,err := os.Open(tarFileName) if err != nil{ fmt.Printf("%v",err) return } defer fw.Close() tr := tar.NewReader(fw) for{ hdr,err := tr.Next() if err == io.EOF{ break } if err != nil{ fmt.Printf("%v",err) continue } fmt.Println("filename:"+hdr.Name) } } func main(){ tarFileName := "test.tar" //tarFileList := []string{"1","2","3"} rootPath := "/home/pijing/goworkspace/gocode" //tarPackage(tarFileName,tarFileList,rootPath) tarReader(rootPath+"/"+tarFileName) }
2.读取写入zip文件
package main import ( "io" "archive/zip" "fmt" "os" "bufio" ) func readFile(path string) string{ var content string = "" file,err := os.Open(path) if err != nil{ fmt.Printf("%v",err) return "" } defer file.Close() inputReader := bufio.NewReader(file) for{ inputString,err := inputReader.ReadString('\n') content += inputString if err == io.EOF{ break } } return content } func zipPackage(zipFileName string,zipFileList []string,rootPath string){ fw,err := os.Create(rootPath+"/"+zipFileName) if err != nil{ fmt.Printf("%v",err) return } defer fw.Close() zw := zip.NewWriter(fw) defer zw.Close() for _,fileItem := range zipFileList{ body := readFile(rootPath+"/"+fileItem) f,err := zw.Create(fileItem) if err != nil{ fmt.Printf("%v",err) continue } _,err1 := f.Write([]byte(body)) if err1 != nil{ fmt.Printf("%v",err1) continue } } fmt.Println("done!") } func zipReader(zipFileName string){ r,err := zip.OpenReader(zipFileName) if err != nil{ fmt.Printf("%v",err) return } defer r.Close() for _,f := range r.File{ fmt.Println("file:"+f.Name) } } func main(){ zipFileName := "test.zip" // zipFileList := []string{"1","2","3"} rootPath := "/home/pijing/goworkspace/gocode" // zipPackage(zipFileName,zipFileList,rootPath) zipReader(rootPath+"/"+zipFileName) }
有疑问加站长微信联系(非本文作者)