1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-11 16:22:26 +08:00

feat: add ClearFile, ReadFileToString, ReadFileByLine into file.go

This commit is contained in:
dudaodong
2021-12-09 20:19:13 +08:00
parent 188d52cd9d
commit 3021985df9
3 changed files with 87 additions and 6 deletions

View File

@@ -5,6 +5,7 @@
package fileutil
import (
"bufio"
"errors"
"io"
"io/ioutil"
@@ -75,6 +76,53 @@ func CopyFile(srcFilePath string, dstFilePath string) error {
}
}
//ClearFile write empty string to path file
func ClearFile(path string) error {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0777)
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString("")
return err
}
//ReadFileToString return string of file content
func ReadFileToString(path string) (string, error) {
bytes, err := ioutil.ReadFile(path)
if err != nil {
return "", err
}
return string(bytes), nil
}
// ReadFileByLine
func ReadFileByLine(path string)([]string, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
res := make([]string, 0)
buf := bufio.NewReader(f)
for {
line, _, err := buf.ReadLine()
l := string(line)
if err == io.EOF {
break
}
if err != nil {
continue
}
res = append(res, l)
}
return res, nil
}
// ListFileNames return all file names in the path
func ListFileNames(path string) ([]string, error) {
if !IsExist(path) {