package fileutils import ( "errors" "fmt" "io" "os" "path/filepath" "strings" "github.com/sirupsen/logrus" ) // 判断所给路径文件/文件夹是否存在 func Exists(path string) bool { _, err := os.Stat(path) //os.Stat获取文件信息 if err != nil { return os.IsExist(err) } return true } // 判断所给路径是否为文件夹 func IsDir(path string) bool { s, err := os.Stat(path) if err != nil { return false } return s.IsDir() } // 判断所给路径是否为文件 func IsFile(path string) bool { return !IsDir(path) } func CopyDir(srcPath string, destPath string) error { //检测目录正确性 if srcInfo, err := os.Stat(srcPath); err != nil { logrus.Error(err) return err } else { if !srcInfo.IsDir() { e := errors.New("srcPath不是一个正确的目录!") logrus.Error(err) return e } } if destInfo, err := os.Stat(destPath); err != nil { logrus.Error(err) return err } else { if !destInfo.IsDir() { e := errors.New("destInfo不是一个正确的目录!") logrus.Error(e) return e } } err := filepath.Walk(srcPath, func(path string, f os.FileInfo, err error) error { if f == nil { return err } if !f.IsDir() { path := strings.Replace(path, "\\", "/", -1) destNewPath := strings.Replace(path, srcPath, destPath, -1) //fmt.Println("复制文件:" + path + " 到 " + destNewPath) copyFile(path, destNewPath) } return nil }) if err != nil { logrus.Error(err) } return err } //生成目录并拷贝文件 func copyFile(src, dest string) (w int64, err error) { srcFile, err := os.Open(src) if err != nil { fmt.Println(err.Error()) return } defer srcFile.Close() //分割path目录 destSplitPathDirs := strings.Split(dest, "/") //检测时候存在目录 destSplitPath := "" for index, dir := range destSplitPathDirs { if index < len(destSplitPathDirs)-1 { destSplitPath = destSplitPath + dir + "/" b, _ := pathExists(destSplitPath) if !b { fmt.Println("创建目录:" + destSplitPath) //创建目录 err := os.Mkdir(destSplitPath, os.ModePerm) if err != nil { logrus.Error(err) } } } } dstFile, err := os.Create(dest) if err != nil { logrus.Error(err) return } defer dstFile.Close() return io.Copy(dstFile, srcFile) } //检测文件夹路径时候存在 func pathExists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return false, err }