代码拉取完成,页面将自动刷新
package common
import (
"bufio"
"io"
"log"
"os"
"os/exec"
"os/user"
"path"
"path/filepath"
"regexp"
"runtime"
"strings"
)
// FileRename 文件重命名
func FileRename(oldFile string, newFile string) error {
return os.Rename(oldFile, newFile)
}
func FileCopy(srcFile string, destFile string) bool {
open, err := os.Open(srcFile)
if err != nil {
ThrowException("copy.os.Open", err.Error())
return false
}
if !FileDirsReadyForWriteFile(destFile) {
log.Println("copy.FileDirsReadyForWriteFile failed")
return false
}
create, err2 := os.Create(destFile)
if err2 != nil {
ThrowException("copy.os.Create", err2.Error())
return false
}
wt := bufio.NewWriter(create)
length, err3 := io.Copy(wt, open)
if err3 != nil {
ThrowException("copy.io.Copy", err3.Error())
return false
}
err = open.Close()
if err != nil {
ThrowException("copy.open.Close", err.Error())
}
err = wt.Flush()
if err != nil {
ThrowException("copy.wt.Flush", err.Error())
}
err = create.Close()
if err != nil {
ThrowException("copy.create.Close", err.Error())
}
log.Println("copy.length 字节数:", length)
return true
}
func FileRead(file string) string {
//读取
bytesRead, err := os.ReadFile(file)
if err != nil {
ThrowException("读取文件失败:", err)
}
return string(bytesRead)
}
func FileReadBytes(file string) []byte {
//读取
bytesRead, err := os.ReadFile(file)
if err != nil {
ThrowException("读取文件失败:", err)
}
return bytesRead
}
func FileReadBytesIfExists(defaultValue []byte, filePaths ...string) []byte {
fileImg := FileOf(filePaths...)
if FileExists(fileImg) {
return FileReadBytes(fileImg)
}
return defaultValue
}
func FileWrite(file string, content string) bool {
return FileWriteBytes(file, []byte(content))
}
func FileWriteBytes(file string, bytes []byte) bool {
strings.LastIndex(file, string(os.PathSeparator))
if !FileExists(file) {
dir := FileGetParentDir(file)
//创建目录
if !FileExists(dir) {
FileCreateDirs(dir)
}
}
//写入
err := os.WriteFile(file, bytes, 0666)
if err != nil {
ThrowException("写入文件失败:", err.Error())
return false
}
return true
}
// FileGetFilename 获取文件名(带后缀的)
func FileGetFilename(file string) string {
//path.Base 只能处理/路径的
file = strings.Replace(file, "\\", "/", -1)
return path.Base(file)
}
// FileGetSuffix 获取文件后缀(带点的)
func FileGetSuffix(file string) string {
return path.Ext(file)
}
// FileGetName 获取文件名(不带后缀)
func FileGetName(file string) string {
return strings.TrimSuffix(FileGetFilename(file), FileGetSuffix(file))
}
// FileGetFiles 获取该目录下的文件
func FileGetFiles(file string) []string {
//获取文件或目录相关信息
files, err := os.ReadDir(file)
if err != nil {
ThrowException("获取文件集失败", err.Error())
}
i := 0
for _, info := range files {
if info.IsDir() {
} else {
i++
}
}
arr := make([]string, i)
i = 0
for _, info := range files {
if info.IsDir() {
} else {
arr[i] = FileOf(file, info.Name())
i++
}
}
return arr
}
// // FileGetFiles 获取该目录下的目录
func FileGetDirs(file string) []string {
//获取文件或目录相关信息
files, err := os.ReadDir(file)
if err != nil {
ThrowException("获取目录集失败", err.Error())
}
i := 0
for _, info := range files {
if info.IsDir() {
i++
}
}
arr := make([]string, i)
i = 0
for _, info := range files {
if info.IsDir() {
arr[i] = FileOf(file, info.Name())
i++
}
}
return arr
}
// FileGetChildren 获取该目录下文件和目录
func FileGetChildren(file string) []string {
//获取文件或目录相关信息
files, err := os.ReadDir(file)
if err != nil {
ThrowException("获取文件子集失败", err.Error())
}
arr := make([]string, len(files))
for i, info := range files {
arr[i] = FileOf(file, info.Name())
}
return arr
}
// FileIsAbsolutePath 是否为绝对路径
func FileIsAbsolutePath(file string) bool {
f := false
switch runtime.GOOS {
//case "darwin":
//case "linux", "freebsd":
case "windows":
f = strings.Contains(file, ":")
default:
f = StrStartsWith(file, "/")
}
return f
}
// FileIsFileByFilename 根据文件名后缀来判断是否为文件(无法判别无后缀的文件)
func FileIsFileByFilename(file string) bool {
filename := FileGetFilename(file)
return strings.Contains(filename, ".")
}
// FileOf 整合文件路径
func FileOf(filePaths ...string) string {
pathSeparator := string(os.PathSeparator)
size := len(filePaths)
temp := ""
for i := 0; i < size; i++ {
tmp := filePaths[i]
tmp = strings.Replace(tmp, "\\", "/", -1)
if i == 0 {
temp = tmp
} else {
count := 0
if StrStartsWith(tmp, "../") {
count = strings.Count(tmp, "../")
tmp = StrSubstringBegin(tmp, count*3)
} else if StrStartsWith(tmp, "./") {
tmp = StrSubstringBegin(tmp, 2)
// 检查是否为文件名
} else if StrStartsWith(tmp, "/") || regexp.MustCompile(`^\.[a-zA-Z0-9]{1,10}$`).MatchString(tmp) {
// 如果是文件名,则直接追加
temp += tmp
continue
}
if count == 0 {
if StrEndsWith(temp, "/") {
temp += tmp
} else {
temp += "/" + tmp
}
} else {
for j := 0; j < count; j++ {
index := strings.LastIndex(temp, "/")
temp = StrSubstringEnd(temp, index)
}
temp += "/" + tmp
}
}
}
temp = strings.Replace(temp, "\\", pathSeparator, -1)
temp = strings.Replace(temp, "/", pathSeparator, -1)
return temp
}
// FileDirsReadyForWriteFile 提前向准备写入的文件目录做准备 true表示存在已经准备就绪
func FileDirsReadyForWriteFile(file string) bool {
directory := FileGetParentDir(file)
if FileExists(directory) {
return true
} else {
return FileCreateDirs(directory)
}
}
// 用户主目录的路径(如果有的话)。
func FileGetUserDir() string {
currentUser, err := user.Current()
if err != nil {
log.Fatalf(err.Error())
}
return currentUser.HomeDir
}
// 特定于操作系统的路径分隔符
func FileSeparator() string {
return string(os.PathSeparator)
}
// 特定于操作系统的路径列表分隔符
func FilePathSeparator() string {
return string(os.PathListSeparator)
}
// FileGetParentDir 获取上级目录
func FileGetParentDir(file string) string {
pathSeparator := string(os.PathSeparator)
if len(file) == 0 {
ThrowException("file path length is zero")
}
return StrSubstring(file, 0, strings.LastIndex(file, pathSeparator))
}
// FileGetAPPLocal 获取用户的本地应用数据目录,如C:\Users\zhangsan\AppData\Local
func FileGetAPPLocal() string {
localAppData := os.Getenv("LOCALAPPDATA")
if localAppData == "" {
return FileGetCurrentDir()
} else {
return localAppData
}
}
// FileGetCurrentDir 获取当前目录
func FileGetCurrentDir() string {
return FileGetParentDir(FileGetCurrentFilePath())
}
// FileGetExecDir 获取执行时的当前目录
func FileGetExecDir() string {
pwd, _ := os.Getwd()
return pwd
}
func FileGetExecFile() string {
exe_, _ := filepath.Abs(os.Args[0])
return exe_
}
// FileGetCurrentFilePath 获取exe执行文件路径(最终方案-全兼容)包含后缀
func FileGetCurrentFilePath() string {
dir := getCurrentAbPathByExecutable()
tmpDir, _ := filepath.EvalSymlinks(os.TempDir())
if strings.Contains(dir, tmpDir) {
return getCurrentAbPathByLookPath()
}
return dir
}
// 获取当前执行文件绝对路径
func getCurrentAbPathByExecutable() string {
exePath, err := os.Executable()
if err != nil {
log.Fatal(err)
}
res, _ := filepath.EvalSymlinks(exePath)
return res
}
// 获取当前方法文件执行绝对路径(go run)
func getCurrentAbPathByCaller() string {
var abPath string
_, filename, _, ok := runtime.Caller(0)
if ok {
//C:\Projects\workspace-idea\JavaFX\go\src\common
//abPath = path.Dir(filename)
abPath = filename
}
return abPath
}
// 获取当前执行文件绝对路径(go run)
func getCurrentAbPathByLookPath() string {
//C:\Users\QiuBo\AppData\Local\Temp\___go_build_upgrade_go.exe
dir, dirErr := exec.LookPath(os.Args[0])
if dirErr != nil {
return getCurrentAbPathByCaller()
}
//fmt.Println("exec.LookPath",dir)
return dir
}
func FileCreateDirs(path string) bool {
err := os.MkdirAll(path, 0750)
if err != nil {
ThrowException("创建目录失败:", err.Error())
return false
}
return true
}
// FileExists 判断所给路径文件/文件夹是否存在 true存在
func FileExists(path string) bool {
_, err := os.Stat(path) //os.Stat获取文件信息
if err != nil {
if os.IsExist(err) {
return true
}
return false
}
return true
}
// FileIsDir 判断所给路径是否为文件夹 false不存在或不是目录
func FileIsDir(path string) bool {
s, err := os.Stat(path)
if err != nil {
return false
}
return s.IsDir()
}
// FileIsFile 判断所给路径是否为文件 false不存在或不是文件
func FileIsFile(path string) bool {
s, err := os.Stat(path)
if err != nil {
return false
}
return !s.IsDir()
}
// FileDelete 删除文件,可能会抛出异常 不能中断的地方建议用err :=recover()接收抛出的异常
//
// defer func() {
// if err := recover(); err != nil {
// fmt.Println("occur error")
// fmt.Println(err)
// }
// }()
func FileDelete(file string) bool {
err := os.RemoveAll(file)
if err != nil {
ThrowException("删除全部文件失败:", err.Error())
return false
}
return true
}
// FileSumCheckByCRC32 通过CRC32校验两个文本是否一致
func FileSumCheckByCRC32(file1, file2 string) bool {
if FileExists(file1) && FileExists(file1) {
return CRC32Hash(FileReadBytes(file1)) == CRC32Hash(FileReadBytes(file2))
}
return false
}
// 根据跟路径分别拼接资源文件目录名,如果存在则返回,不存在返回第一个名字
func FileFindOnlyResourceName(root string, names ...string) string {
onlyName := names[0]
for _, name := range names {
f := FileOf(root, name)
if FileExists(f) {
onlyName = name
break
}
log.Println("资源文件目录不存在:", f, name)
}
return onlyName
}
// 根据跟路径分别拼接资源文件目录名,如果存在则返回目录路径,不存在返回第一个目录路径
func FileFindOnlyResource(root string, names ...string) string {
onlyPath := FileOf(root, names[0])
for _, name := range names {
f := FileOf(root, name)
if FileExists(f) {
onlyPath = f
break
}
log.Println("资源文件目录不存在:", f, name)
}
return onlyPath
}
// 根据提供的绝对路径寻找存在的资源目录,如果存在则返回目录路径,不存在返回第一个目录路径
func FileFindOnlyResourcePath(paths ...string) string {
onlyPath := paths[0]
for _, path := range paths {
if FileExists(path) {
onlyPath = path
break
}
log.Println("资源文件目录不存在:", path)
}
return onlyPath
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。