How can I read a whole file into a string variable

前端 未结 5 1074
别跟我提以往
别跟我提以往 2020-11-29 19:32

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?

5条回答
  •  野性不改
    2020-11-29 20:11

    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.

提交回复
热议问题