基础API

  • filepath.Base(path string): 文件名,会自动忽略掉结尾的”/“
  • filepath.Dir(path string): path 中的 directory name
  • filepath.Join(elem …string): 路径拼接
  • os.MkdirAll(path string, perm FileMode): 创建所有路径上的文件夹,并指明文件夹权限,如 os.MkdirAll(dirpath, os.ModePerm)
  • os.Stat(path string): 返回文件或文件夹详情信息,有 Name、Size、Mode、ModTime、IsDir、Sys 方法
  • os.IsExist(err error): 根据返回的错误判断路径是否存在,比如将 os.Stat 返回的错误传递给 os.IsExist
  • os.Create(name string): 创建或覆盖文件
  • os.Open(name string): 返回文件读取流
  • io.Copy(dst Writer, src Reader): 复制流至目标
  • os.Chtimes(name string, atime time.Time, mtime time.Time): 修改文件 atime(访问时间) 和 mtime(修改时间)
  • os.Rename(oldpath, newpath string): 文件移动或重命名
  • os.RemoveAll(path string): 移除文件或文件夹
  • os.TempDir(): 返回系统临时目录
  • ioutil.ReadDir(dirname string): 返回文件信息切换,文件信息同 os.Stat

常见操作

  • 文件读取
  1. <!-- 将整个文件读取到内存 -->
  2. data, _ := ioutil.ReadFile("abc.txt")
  3. fmt.Println(string(data))
  4. <!-- 或者先Open文件获取*os.File,再Read -->
  5. file, _ := os.Open("abc.txt")
  6. data, _ = ioutil.ReadAll(file)
  7. fmt.Println(string(data))
  8. <!-- 分块读取文件 -->
  9. f, _ := os.Open("abc.txt")
  10. r := bufio.NewReader(f)
  11. b := make([]byte, 3)
  12. for {
  13. _, err := r.Read(b)
  14. if err != nil {
  15. fmt.Println("Error reading file:", err)
  16. break
  17. }
  18. fmt.Println(string(b))
  19. }
  20. <!-- 逐行读取文件 -->
  21. f2, _ := os.Open("abc.txt")
  22. s := bufio.NewScanner(f2)
  23. for s.Scan() {
  24. fmt.Println(s.Text())
  25. }
  • 文件写入
  1. dst, _ := os.Create("abc.txt")
  2. defer dst.Close()
  3. <!-- 字符串写入文件 -->
  4. dst.WriteString("lalala1")
  5. <!-- 将字符串一行一行的写入文件 -->
  6. fmt.Fprintln(dst, "lalala2")
  7. <!-- 文件拷贝 -->
  8. file, _ := os.Open("README.md")
  9. defer file.Close()
  10. io.Copy(dst, file)
  11. <!-- Seek(offset int64, whence int),whence: 0 开头位置,1 当前偏移量,2 结束位置 -->
  12. file.Seek(0, 0)
  13. io.Copy(dst, file)
  • 文件追加
  1. <!-- OpenFile(name string, flag int, perm FileMode),flag: O_RDONLY,O_WRONLY,O_RDWR,O_APPEND,O_CREATE等 -->
  2. f, _ := os.OpenFile("abc.txt", os.O_APPEND|os.O_WRONLY, 0644)
  3. defer f.Close()
  4. fmt.Fprintln(f, "233")
  • 改变文件修改时间
  1. dstFi, _ := os.Stat(dstPath)
  2. modTime := dstFi.ModTime()
  3. os.Chtimes(dirpath, modTime, modTime)

读取请求体

  1. var file io.Reader = nil
  2. <!-- file的二进制内容都在body部分 -->
  3. file = req.Body
  4. <!-- 兼容旧的multipart/form-data的形式,推迟到要读取body的multipar form了才开始解析,并给2G缓冲区 -->
  5. req.ParseMultipartForm(2 << 30)
  6. mpFile, _, _ := req.FormFile("file")
  7. if mpFile != nil {
  8. defer mpFile.Close()
  9. }
  10. if req.MultipartForm != nil {
  11. // Seen from go source code, req.MultipartForm not nil after call ParseMultipartForm
  12. defer req.MultipartForm.RemoveAll()
  13. }
  14. file = mpFile
  15. ...
  16. <!-- 将请求头写入目标文件 -->
  17. io.Copy(dst, file)