我如何在Golang中将整个文件读入字符串变量? [英] How can I read a whole file into a string variable in Golang?
本文介绍了我如何在Golang中将整个文件读入字符串变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Golang中有一个函数允许我读取整个文件吗?
我有很多小文件,我不想逐行阅读。转换为字符串变量?
解决方案
使用 ioutil.ReadFile :
$ b
func ReadFile(filename string)([] byte,error)
ReadFile读取由filename命名的文件并返回内容。成功的调用
返回err == nil,而不是err == EOF。由于ReadFile读取整个文件,因此它不会将
作为一个EOF从Read读取为一个报告错误。
您会得到 []字节
而不是字符串
。如果真的必要,它可以被转换:
s:=字符串(buf)
I have lots of small files, I don't want to read them line by line.
Is there a function in Golang to let me read a whole file into a string variable?
解决方案
Use 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.
You will get a []byte
instead of a string
. It can be converted if really necessary:
s := string(buf)
这篇关于我如何在Golang中将整个文件读入字符串变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文