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?
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?
This is how I did it:
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.
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.
If you just want the content as
string
, then the simple solution is to use theReadFile
function from theio/ioutil
package. This function returns a slice ofbytes
which you can easily convert to astring
.Use
ioutil.ReadFile
:You will get a
[]byte
instead of astring
. It can be converted if really necessary: