创建文件前,创建目录

This commit is contained in:
白茶清欢 2023-01-13 11:59:14 +08:00
parent f7309c25b6
commit 9f12853333

View File

@ -13,6 +13,7 @@ import (
"errors" "errors"
"io" "io"
"os" "os"
"path/filepath"
"strings" "strings"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
@ -144,6 +145,14 @@ func (f *fileOperate) Create() error {
return errors.New("文件不存在, 且不允许自动创建 : " + f.filePath) return errors.New("文件不存在, 且不允许自动创建 : " + f.filePath)
} }
} }
// 创建目录
fileArr := strings.Split(f.filePath, string(filepath.Separator))
if len(fileArr) >= 2 {
pathStr := strings.Join(fileArr[0:len(fileArr)-1], string(filepath.Separator))
if err = os.MkdirAll(pathStr, 0777); nil != err {
return errors.New("文件目录创建失败 : " + err.Error())
}
}
f.fileHandler, err = os.OpenFile(f.filePath, f.openFlag, f.permission) f.fileHandler, err = os.OpenFile(f.filePath, f.openFlag, f.permission)
return err return err
} }