Golang 实现文件解压缩与拷贝

前端之家收集整理的这篇文章主要介绍了Golang 实现文件解压缩与拷贝前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. package main
  2.  
  3. import (
  4. "archive/tar"
  5. "compress/gzip"
  6. "fmt"
  7. "io"
  8. "os"
  9. "path"
  10. )
  11.  
  12. // main functions shows how to TarGz a directory/file and
  13. // UnTarGz a file
  14. // Gzip and tar from source directory or file to destination file
  15. // you need check file exist before you call this function
  16.  
  17. func main() {
  18. os.Mkdir("/home/ty4z2008/tar",0777)
  19. w,err := CopyFile("/home/ty4z2008/tar/1.pdf","/home/ty4z2008/src/1.pdf")
  20. //targetfile,sourcefile
  21. if err != nil {
  22. fmt.Println(err.Error())
  23. }
  24. fmt.Println(w)
  25.  
  26. TarGz("/home/ty4z2008/tar/1.pdf","/home/ty4z2008/test.tar.gz") //压缩
  27. //UnTarGz("/home/ty4z2008/1.tar.gz","/home/ty4z2008") //解压
  28. os.RemoveAll("/home/ty4z2008/tar")
  29.  
  30. fmt.Println("ok")
  31. }
  32.  
  33. func TarGz(srcDirPath string,destFilePath string) {
  34. fw,err := os.Create(destFilePath)
  35. if err != nil {
  36. panic(err)
  37. }
  38. defer fw.Close()
  39.  
  40. // Gzip writer
  41. gw := gzip.NewWriter(fw)
  42. defer gw.Close()
  43.  
  44. // Tar writer
  45. tw := tar.NewWriter(gw)
  46. defer tw.Close()
  47.  
  48. // Check if it's a file or a directory
  49. f,err := os.Open(srcDirPath)
  50. if err != nil {
  51. panic(err)
  52. }
  53. fi,err := f.Stat()
  54. if err != nil {
  55. panic(err)
  56. }
  57. if fi.IsDir() {
  58. // handle source directory
  59. fmt.Println("Cerating tar.gz from directory...")
  60. tarGzDir(srcDirPath,path.Base(srcDirPath),tw)
  61. } else {
  62. // handle file directly
  63. fmt.Println("Cerating tar.gz from " + fi.Name() + "...")
  64. tarGzFile(srcDirPath,fi.Name(),tw,fi)
  65. }
  66. fmt.Println("Well done!")
  67. }
  68.  
  69. // Deal with directories
  70. // if find files,handle them with tarGzFile
  71. // Every recurrence append the base path to the recPath
  72. // recPath is the path inside of tar.gz
  73. func tarGzDir(srcDirPath string,recPath string,tw *tar.Writer) {
  74. // Open source diretory
  75. dir,err := os.Open(srcDirPath)
  76. if err != nil {
  77. panic(err)
  78. }
  79. defer dir.Close()
  80.  
  81. // Get file info slice
  82. fis,err := dir.Readdir(0)
  83. if err != nil {
  84. panic(err)
  85. }
  86. for _,fi := range fis {
  87. // Append path
  88. curPath := srcDirPath + "/" + fi.Name()
  89. // Check it is directory or file
  90. if fi.IsDir() {
  91. // Directory
  92. // (Directory won't add unitl all subfiles are added)
  93. fmt.Printf("Adding path...%s\n",curPath)
  94. tarGzDir(curPath,recPath+"/"+fi.Name(),tw)
  95. } else {
  96. // File
  97. fmt.Printf("Adding file...%s\n",curPath)
  98. }
  99.  
  100. tarGzFile(curPath,fi)
  101. }
  102. }
  103.  
  104. // Deal with files
  105. func tarGzFile(srcFile string,tw *tar.Writer,fi os.FileInfo) {
  106. if fi.IsDir() {
  107. // Create tar header
  108. hdr := new(tar.Header)
  109. // if last character of header name is '/' it also can be directory
  110. // but if you don't set Typeflag,error will occur when you untargz
  111. hdr.Name = recPath + "/"
  112. hdr.Typeflag = tar.TypeDir
  113. hdr.Size = 0
  114. //hdr.Mode = 0755 | c_ISDIR
  115. hdr.Mode = int64(fi.Mode())
  116. hdr.ModTime = fi.ModTime()
  117.  
  118. // Write hander
  119. err := tw.WriteHeader(hdr)
  120. if err != nil {
  121. panic(err)
  122. }
  123. } else {
  124. // File reader
  125. fr,err := os.Open(srcFile)
  126. if err != nil {
  127. panic(err)
  128. }
  129. defer fr.Close()
  130.  
  131. // Create tar header
  132. hdr := new(tar.Header)
  133. hdr.Name = recPath
  134. hdr.Size = fi.Size()
  135. hdr.Mode = int64(fi.Mode())
  136. hdr.ModTime = fi.ModTime()
  137.  
  138. // Write hander
  139. err = tw.WriteHeader(hdr)
  140. if err != nil {
  141. panic(err)
  142. }
  143.  
  144. // Write file data
  145. _,err = io.Copy(tw,fr)
  146. if err != nil {
  147. panic(err)
  148. }
  149. }
  150. }
  151.  
  152. // Ungzip and untar from source file to destination directory
  153. // you need check file exist before you call this function
  154. func UnTarGz(srcFilePath string,destDirPath string) {
  155. fmt.Println("UnTarGzing " + srcFilePath + "...")
  156. // Create destination directory
  157. os.Mkdir(destDirPath,os.ModePerm)
  158.  
  159. fr,err := os.Open(srcFilePath)
  160. if err != nil {
  161. panic(err)
  162. }
  163. defer fr.Close()
  164.  
  165. // Gzip reader
  166. gr,err := gzip.NewReader(fr)
  167. if err != nil {
  168. panic(err)
  169. }
  170. defer gr.Close()
  171.  
  172. // Tar reader
  173. tr := tar.NewReader(gr)
  174.  
  175. for {
  176. hdr,err := tr.Next()
  177. if err == io.EOF {
  178. // End of tar archive
  179. break
  180. }
  181. //handleError(err)
  182. fmt.Println("UnTarGzing file..." + hdr.Name)
  183. // Check if it is diretory or file
  184. if hdr.Typeflag != tar.TypeDir {
  185. // Get files from archive
  186. // Create diretory before create file
  187. os.MkdirAll(destDirPath+"/"+path.Dir(hdr.Name),os.ModePerm)
  188. // Write data to file
  189. fw,_ := os.Create(destDirPath + "/" + hdr.Name)
  190. if err != nil {
  191. panic(err)
  192. }
  193. _,err = io.Copy(fw,tr)
  194. if err != nil {
  195. panic(err)
  196. }
  197. }
  198. }
  199. fmt.Println("Well done!")
  200. }
  201.  
  202. //Copyfile
  203. func CopyFile(dstName,srcName string) (written int64,err error) {
  204. src,err := os.Open(srcName)
  205. if err != nil {
  206. return
  207. }
  208. defer src.Close()
  209. dst,err := os.OpenFile(dstName,os.O_WRONLY|os.O_CREATE,0644)
  210. if err != nil {
  211. return
  212. }
  213. defer dst.Close()
  214. return io.Copy(dst,src)
  215. }

猜你在找的Go相关文章