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.

96 lines
2.1 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 (
"bufio"
"fmt"
"io"
"log"
"os"
)
// 判断所给路径文件/文件夹是否存在
func Exists(path string) bool {
_, err := os.Stat(path) //os.Stat获取文件信息
if err != nil {
if os.IsExist(err) {
return true
}
return false
}
return true
}
/**
功能:按行读取文件
作者:黄海
时间2020-07-08
*/
func ReadLines(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
}
/**
功能:按行写入文件
作者:黄海
时间2020-07-08
*/
func WriteLines(lines []string, path string) error {
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
w := bufio.NewWriter(file)
for _, line := range lines {
fmt.Fprintln(w, line)
}
return w.Flush()
}
/**
功能:读取文件内容
作者:黄海
时间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)
fmt.Println(err.Error())
}
}
//此时文件内容写到buf里面去了写了多少个呢写了n个那么我们再写到data里面去
data = append(data, buf[:n]...)
}
return string(data)
}