0. 概述

在开发过程中,无论是配置读取还是数据持久化,多多少少都是离不开文件操作的,在这篇文章中,我总结了一下 Go 语言中关于文件的操作。

1. 一行一行读取文件

  1. [root@liqiang.io]# cat line.go
  2. func main() {
  3. file, _ := os.Open("/path/to/file.txt")
  4. defer file.Close()
  5. scanner := bufio.NewScanner(file)
  6. for scanner.Scan() {
  7. fmt.Println(scanner.Text())
  8. }
  9. if err := scanner.Err(); err != nil {
  10. panic(err)
  11. }
  12. }

2. 读取一个字节

  1. [root@liqiang.io]# cat one-byte.go
  2. func main() {
  3. file, _ := os.Open("/path/to/file.txt")
  4. defer file.Close()
  5. var buf = make([]byte, 1)
  6. _, err := f.read(buf)
  7. }

3. 打开文件

  1. [root@liqiang.io]# cat open_file.go
  2. f, err := os.Open(path.Join(h.cfg.ThemePath, theme, filePath))
  3. if err != nil {
  4. panic(err)
  5. }

4. 获取文件大小

  1. [root@liqiang.io]# cat file_size.go
  2. fi, err := f.Stat()
  3. if err != nil {
  4. // Could not obtain stat, handle error
  5. }
  6. fmt.Printf("The file is %d bytes long", fi.Size())

5. 判断文件是否存在

  1. [root@liqiang.io]# cat file_exists.go
  2. func fileExists(filename string) bool {
  3. info, err := os.Stat(filename)
  4. if os.IsNotExist(err) {
  5. return false
  6. }
  7. return !info.IsDir()
  8. }