go_gin_tmpl/utils/file.go
2022-05-09 09:00:14 +08:00

64 lines
1.1 KiB
Go

package utils
import (
"fmt"
"github.com/duke-git/lancet/v2/fileutil"
"os"
)
type fileUtils struct{}
func FileUtils() *fileUtils {
return &fileUtils{}
}
func (f fileUtils) CheckIsExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
// CheckAndCreate 判断文件名是否存在,不存在就创建
func (f fileUtils) CheckAndCreate(path string) error {
exists, err := f.CheckIsExists(path)
if err != nil {
return err
}
if !exists {
err = os.MkdirAll(path, os.ModePerm)
if err != nil {
return err
}
}
return nil
}
// DelPath 删除目录下的所有文件和目录本身
func (f fileUtils) DelPath(path string) error {
files, err := fileutil.ListFileNames(path)
if err != nil {
return err
}
for _, file := range files {
// 如果是目录,则递归删除
if fileutil.IsDir(file) {
err = f.DelPath(file)
if err != nil {
return err
}
} else {
err = fileutil.RemoveFile(fmt.Sprintf("%s/%s", path, file))
if err != nil {
return err
}
}
}
_ = fileutil.RemoveFile(path)
return nil
}