string 如何将整个文件读入字符串变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13514184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I read a whole file into a string variable
提问by WoooHaaaa
I have lots of small files, I don't want to read them line by line.
我有很多小文件,我不想逐行阅读。
Is there a function in Go that will read a whole file into a string variable?
Go中是否有一个函数可以将整个文件读入字符串变量?
回答by zzzz
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.
ReadFile 读取以 filename 命名的文件并返回内容。成功的调用返回 err == nil,而不是 err == EOF。因为 ReadFile 读取整个文件,它不会将 Read 中的 EOF 视为要报告的错误。
You will get a []byte
instead of a string
. It can be converted if reallynecessary:
你会得到一个[]byte
而不是一个string
。如果确实需要,可以转换它:
s := string(buf)
回答by openwonk
If you just want the content as string
, then the simple solution is to use the ReadFile
function from the io/ioutil
package. This function returns a slice of bytes
which you can easily convert to a string
.
如果您只想要内容为string
,那么简单的解决方案是使用包中的ReadFile
功能io/ioutil
。此函数返回一个切片bytes
,您可以轻松地将其转换为string
.
package main
import (
"fmt"
"io/ioutil"
)
func main() {
b, err := ioutil.ReadFile("file.txt") // just pass the file name
if err != nil {
fmt.Print(err)
}
fmt.Println(b) // print the content as 'bytes'
str := string(b) // convert content to a 'string'
fmt.Println(str) // print the content as a 'string'
}
回答by Running Wild
I think the best thing to do, if you're really concerned about the efficiency of concatenating all of these files, is to copy them all into the same bytes buffer.
我认为最好的办法是,如果您真的关心连接所有这些文件的效率,那就是将它们全部复制到相同的字节缓冲区中。
buf := bytes.NewBuffer(nil)
for _, filename := range filenames {
f, _ := os.Open(filename) // Error handling elided for brevity.
io.Copy(buf, f) // Error handling elided for brevity.
f.Close()
}
s := string(buf.Bytes())
This opens each file, copies its contents into buf, then closes the file. Depending on your situation you may not actually need to convert it, the last line is just to show that buf.Bytes() has the data you're looking for.
这将打开每个文件,将其内容复制到 buf,然后关闭文件。根据您的情况,您可能实际上不需要转换它,最后一行只是为了表明 buf.Bytes() 具有您要查找的数据。
回答by Mo-Gang
This is how I did it:
我是这样做的:
package main
import (
"fmt"
"os"
"bytes"
"log"
)
func main() {
filerc, err := os.Open("filename")
if err != nil{
log.Fatal(err)
}
defer filerc.Close()
buf := new(bytes.Buffer)
buf.ReadFrom(filerc)
contents := buf.String()
fmt.Print(contents)
}
回答by fwhez
I'm not with computer,so I write a draft. You might be clear of what I say.
我不会用电脑,所以我写了一个草稿。你可能很清楚我说的话。
func main(){
const dir = "/etc/"
filesInfo, e := ioutil.ReadDir(dir)
var fileNames = make([]string, 0, 10)
for i,v:=range filesInfo{
if !v.IsDir() {
fileNames = append(fileNames, v.Name())
}
}
var fileNumber = len(fileNames)
var contents = make([]string, fileNumber, 10)
wg := sync.WaitGroup{}
wg.Add(fileNumber)
for i,_:=range content {
go func(i int){
defer wg.Done()
buf,e := ioutil.Readfile(fmt.Printf("%s/%s", dir, fileName[i]))
defer file.Close()
content[i] = string(buf)
}(i)
}
wg.Wait()
}