0. 概述
在开发过程中,无论是配置读取还是数据持久化,多多少少都是离不开文件操作的,在这篇文章中,我总结了一下 Go 语言中关于文件的操作。
1. 一行一行读取文件
[root@liqiang.io]# cat line.go
func main() {
file, _ := os.Open("/path/to/file.txt")
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
panic(err)
}
}
2. 读取一个字节
[root@liqiang.io]# cat one-byte.go
func main() {
file, _ := os.Open("/path/to/file.txt")
defer file.Close()
var buf = make([]byte, 1)
_, err := f.read(buf)
}
3. 打开文件
[root@liqiang.io]# cat open_file.go
f, err := os.Open(path.Join(h.cfg.ThemePath, theme, filePath))
if err != nil {
panic(err)
}
4. 获取文件大小
[root@liqiang.io]# cat file_size.go
fi, err := f.Stat()
if err != nil {
// Could not obtain stat, handle error
}
fmt.Printf("The file is %d bytes long", fi.Size())
5. 判断文件是否存在
[root@liqiang.io]# cat file_exists.go
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}