You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
1.9 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package FileUtil
import (
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
)
/**
功能:读取文件内容
作者:黄海
时间2019-12-31
*/
func ReadFileContent(filepath string) string {
file, err := os.Open(filepath)
if err != nil {
log.Print("文件打开失败:", err)
}
defer file.Close()
buf := make([]byte, 12) // 存放文件内容的缓存,相当于中转站
data := make([]byte, 0) // 用来存放文件内容buf读取的内容都会写到data里面去
for {
//无限循环,不断读取
n, err := file.Read(buf)
// 什么时候文件读完呢如果文件读完的话那么err不为nil而是io.EOF
// 所以我们可以进行判断
if err != nil {
//如果err != nil说明出错了但如果还等于io.EOF的话说明读完了因为文件读完err也不为nil。直接break
if err == io.EOF {
break
} else {
//如果错误不是io.EOF的话说明就真的在读取中出现了错误直接panic出来
panic(err)
}
}
//此时文件内容写到buf里面去了写了多少个呢写了n个那么我们再写到data里面去
data = append(data, buf[:n]...)
}
return string(data)
}
/**
功能:获取文件的大小
作者:黄海
时间2020-01-20
*/
func GetFileSize(filename string) int64 {
var result int64
filepath.Walk(filename, func(path string, f os.FileInfo, err error) error {
result = f.Size()
return nil
})
return result
}
/**
功能:写入文件
作者:黄海
时间2020-05-16
*/
func WriteFileContent(filename string, content string) {
var d1 = []byte(content)
ioutil.WriteFile(filename, d1, 0666) //写入文件(字节数组)
}
/**
功能:判断目录是不是存在
作者:黄海
时间2020-05-20
*/
func PathExists(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
return false
}