utils.go 2.4 KB

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