¿Cómo puedo leer un archivo completo en una variable de cadena
Tengo muchos archivos pequeños, no quiero leerlos línea por línea.
¿Hay una función en Go que leerá un archivo completo en una variable de cadena?
4 answers
Uso ioutil.ReadFile
:
func ReadFile(filename string) ([]byte, error)
ReadFile lee el archivo nombrado por filename y devuelve el contenido. Una llamada exitosa devuelve err = = nil, no err = = EOF. Debido a que readFile lee todo el archivo, no trata un EOF de Leído como un error a reportar.
Obtendrá un []byte
en lugar de string
. Se puede convertir si realmente es necesario:
s := string(buf)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-13 21:46:41
Si solo desea el contenido como string
, entonces la solución simple es usar la función ReadFile
del paquete io/ioutil
. Esta función devuelve una porción de bytes
que puede convertir fácilmente a 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'
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-07 05:41:02
Creo que lo mejor que puede hacer, si realmente le preocupa la eficiencia de concatenar todos estos archivos, es copiarlos todos en el mismo búfer de bytes.
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())
Esto abre cada archivo, copia su contenido en buf, luego cierra el archivo. Dependiendo de su situación, es posible que no necesite convertirlo, la última línea es solo para mostrar ese buf.Bytes() tiene los datos que estás buscando.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-22 15:09:51
Así es como lo hice:
package main
import (
"fmt"
"os"
"bytes"
)
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)
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-18 17:19:12