string - 如何将整个文件读入字符串变量

标签 string file go

我有很多小文件,我不想逐行阅读。

Go 中是否有将整个文件读入字符串变量的函数?

最佳答案

使用 ioutil.ReadFile :

func ReadFile(filename string) ([]byte, error)

ReadFile reads the file named by filename and returns the contents. A successful call returns err == nil, not err == EOF. Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported.

你会得到一个 []byte 而不是 string。如果真的需要,可以转换:

s := string(buf)

关于string - 如何将整个文件读入字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13514184/

相关文章:

json - 如何将双引号中的内容与 golang 中的正则表达式进行匹配?

go - 为什么使用goroutine channel ?

Java 字符串参数

java - 从未知路径读取文件

html - 从浏览器下载文件第一次挂起,重复工作

java - 对象序列化的魔法仙女

Emacs 在 go-mode 下找不到 gofmt

string - 使用 PHP 删除字符串中的最后一个数字?

c++ - 尝试将字符串变量与 infile.open() 一起使用在 C++ 中被视为 char

java - JSONObject.put(String) 为每个 '\' 添加 '/'