golang 压缩文件

func compress(file *os.File, prefix string, zw *zip.Writer) error {
   info, err := file.Stat()
   if err != nil {
      return err
   }
   if info.IsDir() {
      if prefix == "" {
         prefix = info.Name()
      } else {
         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.Method = zip.Deflate
      if prefix != "" {
         header.Name = prefix + "/" + header.Name
      }
      if 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
}

转载于:https://my.oschina.net/wgc2010/blog/2874372

你可能感兴趣的:(golang 压缩文件)