一般文件比较小的话可以将文件全部读入内存中,然后转换成string再按行分割一下:
func GetFileContentAsStringLines(filePath string) ([]string, error) {
logger.Infof("get file content as lines: %v", filePath)
result := []string{}
b, err := ioutil.ReadFile(filePath)
if err != nil {
logger.Errorf("read file: %v error: %v", filePath, err)
return result, err
}
s := string(b)
for _, lineStr := range strings.Split(s, "\n") {
lineStr = strings.TrimSpace(lineStr)
if lineStr == "" {
continue
}
result = append(result, lineStr)
}
logger.Infof("get file content as lines: %v, size: %v", filePath, len(result))
return result, nil
}
原文:https://blog.csdn.net/xielingyun/article/details/50324423
网友评论