github.com/eframework-cn/EP.GO.UTIL@v1.0.0/xfs/xfs.go (about) 1 //-----------------------------------------------------------------------// 2 // GNU GENERAL PUBLIC LICENSE // 3 // Version 2, June 1991 // 4 // // 5 // Copyright (C) EFramework, https://eframework.cn, All rights reserved. // 6 // Everyone is permitted to copy and distribute verbatim copies // 7 // of this license document, but changing it is not allowed. // 8 // SEE LICENSE.md FOR MORE DETAILS. // 9 //-----------------------------------------------------------------------// 10 11 // 提供常用的IO操作,如读取文件、写入文件等功能. 12 package xfs 13 14 import ( 15 "io/ioutil" 16 "os" 17 "path/filepath" 18 19 "github.com/eframework-cn/EP.GO.UTIL/xlog" 20 "github.com/eframework-cn/EP.GO.UTIL/xstring" 21 ) 22 23 // 删除文件 24 // path: 文件路径 25 func DeleteFile(path string) bool { 26 if e := os.Remove(path); e != nil { 27 xlog.Info("xfs.DeleteFile: %v", e) 28 return false 29 } else { 30 return true 31 } 32 } 33 34 // 判断文件是否存在 35 // path: 文件路径 36 func FileExist(path string) bool { 37 _, err := os.Lstat(path) 38 return !os.IsNotExist(err) 39 } 40 41 // 判断文件夹是否存在 42 // path: 文件路径 43 // createIsNotExist: 若不存在则创建 44 func PathExist(path string, createIsNotExist ...bool) bool { 45 _, err := os.Lstat(path) 46 if !os.IsNotExist(err) { 47 return true 48 } else { 49 if len(createIsNotExist) == 1 && createIsNotExist[0] { 50 err := os.MkdirAll(path, os.ModePerm) 51 if err != nil { 52 return true 53 } 54 } 55 } 56 return false 57 } 58 59 // 根据文件名称获取该文件的文件夹名称 60 // file: 文件路径 61 func Directory(file string) string { 62 return filepath.Dir(file) 63 } 64 65 // 读取文件(以字符串形式返回) 66 // file: 文件路径 67 func ReadString(file string) string { 68 b, e := ioutil.ReadFile(file) 69 if e != nil { 70 xlog.Info("xfs.ReadString: %v", e) 71 return "" 72 } 73 return xstring.BytesToStr(b) 74 } 75 76 // 读取文件(以字节数组形式返回) 77 // file: 文件路径 78 func ReadBytes(file string) []byte { 79 b, e := ioutil.ReadFile(file) 80 if e != nil { 81 xlog.Info("xfs.ReadBytes: %v", e) 82 return nil 83 } 84 return b 85 } 86 87 // 写入文件(字符串) 88 // file: 文件路径 89 // value: 文件内容 90 // _mode: 文件模式 91 func WriteString(file string, value string, _mode ...os.FileMode) { 92 mode := os.ModeAppend 93 if len(_mode) == 1 { 94 mode = _mode[0] 95 } 96 b := xstring.StrToBytes(value) 97 ioutil.WriteFile(file, b, mode) 98 } 99 100 // 写入文件(字节数组) 101 // file: 文件路径 102 // value: 文件内容 103 // _mode: 文件模式 104 func WriteBytes(file string, value []byte, _mode ...os.FileMode) { 105 mode := os.ModeAppend 106 if len(_mode) == 1 { 107 mode = _mode[0] 108 } 109 ioutil.WriteFile(file, value, mode) 110 }