Add: FileUtils

This commit is contained in:
dennis 2023-09-08 20:49:39 +08:00
parent 582532caff
commit fc61b53643

53
FileUtils.go Normal file
View File

@ -0,0 +1,53 @@
package golanghelper
import (
"errors"
"fmt"
"io"
"os"
)
type FileUtils struct {
}
func (f *FileUtils) CopyFile(srcFilePath, destFilePath string, isOverwrite bool) (err error) {
var srcFileInfo os.FileInfo
srcFileInfo, err = os.Stat(srcFilePath)
if err != nil {
return
}
if !srcFileInfo.Mode().IsRegular() {
return errors.New(fmt.Sprintf("%s is not a regular file", srcFileInfo.Name()))
}
var isNotExist bool
_, err = os.Stat(destFilePath)
if err != nil {
if os.IsNotExist(err) {
isNotExist = true
} else {
return
}
}
var destFile *os.File
if isNotExist == false && isOverwrite == false {
return errors.New("File already exists")
}
destFile, err = os.Create(destFilePath)
if err != nil {
return
}
defer destFile.Close()
sourceFile, err := os.Open(srcFilePath)
if err != nil {
return
}
defer sourceFile.Close()
_, err = io.Copy(destFile, sourceFile)
return
}