utils.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package client
  2. import (
  3. "os"
  4. "fmt"
  5. "errors"
  6. "strings"
  7. "path/filepath"
  8. "io"
  9. )
  10. /**
  11. * 拷贝文件夹,同时拷贝文件夹中的文件
  12. * @param srcPath 需要拷贝的文件夹路径: D:/test
  13. * @param destPath 拷贝到的位置: D:/backup/
  14. */
  15. func CopyDir(srcPath string, destPath string) error {
  16. //检测目录正确性
  17. if srcInfo, err := os.Stat(srcPath); err != nil {
  18. fmt.Println(err.Error())
  19. return err
  20. } else {
  21. if !srcInfo.IsDir() {
  22. e := errors.New("srcPath不是一个正确的目录!")
  23. fmt.Println(e.Error())
  24. return e
  25. }
  26. }
  27. if destInfo, err := os.Stat(destPath); err != nil {
  28. fmt.Println(err.Error())
  29. return err
  30. } else {
  31. if !destInfo.IsDir() {
  32. e := errors.New("destInfo不是一个正确的目录!")
  33. fmt.Println(e.Error())
  34. return e
  35. }
  36. }
  37. //加上拷贝时间:不用可以去掉
  38. //destPath = destPath + "_" + time.Now().Format("20060102150405")
  39. err := filepath.Walk(srcPath, func(path string, f os.FileInfo, err error) error {
  40. if f == nil {
  41. return err
  42. }
  43. if !f.IsDir() {
  44. path := strings.Replace(path, "\\", "/", -1)
  45. destNewPath := strings.Replace(path, srcPath, destPath, -1)
  46. fmt.Println("复制文件:" + path + " 到 " + destNewPath)
  47. copyFile(path, destNewPath)
  48. }
  49. return nil
  50. })
  51. if err != nil {
  52. fmt.Printf(err.Error())
  53. }
  54. return err
  55. }
  56. //生成目录并拷贝文件
  57. func copyFile(src, dest string) (w int64, err error) {
  58. srcFile, err := os.Open(src)
  59. if err != nil {
  60. fmt.Println(err.Error())
  61. return
  62. }
  63. defer srcFile.Close()
  64. //分割path目录
  65. destSplitPathDirs := strings.Split(dest, "/")
  66. //检测时候存在目录
  67. destSplitPath := ""
  68. for index, dir := range destSplitPathDirs {
  69. if index < len(destSplitPathDirs)-1 {
  70. destSplitPath = destSplitPath + dir + "/"
  71. b, _ := pathExists(destSplitPath)
  72. if b == false {
  73. fmt.Println("创建目录:" + destSplitPath)
  74. //创建目录
  75. err := os.Mkdir(destSplitPath, os.ModePerm)
  76. if err != nil {
  77. fmt.Println(err)
  78. }
  79. }
  80. }
  81. }
  82. dstFile, err := os.Create(dest)
  83. if err != nil {
  84. fmt.Println(err.Error())
  85. return
  86. }
  87. defer dstFile.Close()
  88. return io.Copy(dstFile, srcFile)
  89. }
  90. //检测文件夹路径时候存在
  91. func pathExists(path string) (bool, error) {
  92. _, err := os.Stat(path)
  93. if err == nil {
  94. return true, nil
  95. }
  96. if os.IsNotExist(err) {
  97. return false, nil
  98. }
  99. return false, err
  100. }