utils.go 2.3 KB

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