我的博客

Go语言文件操作

目录
  1. 打开文件
  2. 写入
  3. 读取

go 的文档

需要导入 os 包和 path 包

1
2
3
4
import (
"os"
"path"
)

打开文件

1
f, err = os.OpenFile(path.Join("static", "json", "t.json"), os.O_WRONLY | os.O_CREATE, 066)

go 的 os.OpenFile 函数需要三个参数。第一个是文件名,第二个是打开方式,第三个是文件权限。

如果要创建新文件并写入的话,只使用 os.O_WRONLY 是不够的。还要加上 os.O_CREATE 否则返回错误:

open static/json/t.json: The system cannot find the file specified.

写入

1
2
3
4
str := "Hello"
bts := []byte(str)
f.WriteString(str)
f.Write(bts)

读取

1
2
3
 file, err := os.OpenFile(filePath,  os.O_RDWR, 066)     
data := make([]byte, 1024)
count, err := file.Read(data)

评论无需登录,可以匿名,欢迎评论!