以下是对自己项目中,常用到的文件操作
func FileExists(name string) bool {
_, err := os.Stat(name)
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
return false
}
// 根据文件内容生成md5,用于比较文件内容是否相同
func GenerateMD5(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
h := md5.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return fmt.Sprintf("%x", h.Sum(nil)), nil
}
func CompareSum(sum1, sum2 string) bool {
return sum1 == sum2
}
// 判断给定路径是否为文件夹
func IsDir(path string) bool {
s, err := os.Stat(path)
if err != nil {
return false
}
return s.IsDir()
}
// 创建指定文件夹(递归创建)
func CreateDir(dir string) (string, error) {
b, _ := PathExists(dir)
if b {
return dir, nil
}
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
return "", err
}
return dir, nil
}
// 指定文件夹下创建文件
func CreateFile(dir string, filename string, sou io.Reader) (string, error) {
dirPath, err := CreateDir(dir)
if err != nil {
return "", err
}
path := filepath.Join(dirPath, filename)
f, err := os.Create(path)
if err != nil {
return "", err
}
defer f.Close()
_, err = io.Copy(f, sou)
if err != nil {
return "", err
}
return path, nil
}
func GetAllFileFromDir(dirPath string) ([]string, error) {
if !IsDir(dirPath) {
return nil, errors.New("illegal folder path")
}
res := make([]string, 0)
rd, err := ioutil.ReadDir(dirPath)
if err != nil {
return nil, err
}
for _, f := range rd {
if f.IsDir() {
fs, err := GetAllFileFromDir(filepath.Join(dirPath, f.Name()))
if err != nil {
return nil, err
}
res = append(res, fs...)
} else {
res = append(res, filepath.Join(dirPath, f.Name()))
}
}
return res, nil
}
// 提取路径文件名
func ExtractFileName(path string, includeSuf bool) (string, error) {
_, err := PathExists(path)
if err != nil {
return "", err
}
if IsDir(path) {
return "", errors.New("illegal file path")
}
filename := filepath.Base(path)
if includeSuf {
return filename, nil
}
suf := filepath.Ext(filename)
return strings.TrimSuffix(filename, suf), nil
}
// 查找文件名与指定md5值相同的文件
func FindFileByMD5(dir string, md5 string) (string, error) {
if !IsDir(dir) {
return "", errors.New("illegal folder path")
}
paths, err := GetAllFileFromDir(dir)
if err != nil {
return "", err
}
for _, path := range paths {
name, err := ExtractFileName(path, false)
if err != nil {
return "", err
}
if name == md5 {
return path, nil
}
}
return "", nil
}