Golang : Read a file into an array or slice example
Ok, got a junior developer that wants to know how to read a text file content line by line into an array or slice. He is dealing with a legacy software that doesn't send out data either in JSON or XML format. The legacy software output is in text format.
Solution :
Use strings.Split()
function with newline (\n
) as the separator and ioutil.ReadFile()
function.
Here you go!
package main
import (
"fmt"
"io/ioutil"
"os"
"strings"
)
func main() {
if len(os.Args) <= 1 {
fmt.Printf("USAGE : %s <target_filename> \n", os.Args[0])
os.Exit(0)
}
fileName := os.Args[1]
fileBytes, err := ioutil.ReadFile(fileName)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
sliceData := strings.Split(string(fileBytes), "\n")
fmt.Println(sliceData)
}
Reference:
See also : Golang : Display a text file line by line with line number example
By Adam Ng(黃武俊)
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+14.3k Golang : Convert(cast) int to float example
+10.3k Golang : Resolve domain name to IP4 and IP6 addresses.
+5.2k Golang : Intercept, inject and replay HTTP traffics from web server
+44.4k Golang : Use wildcard patterns with filepath.Glob() example
+9.2k Golang : Web(Javascript) to server-side websocket example
+6.4k Golang : When to use make or new?
+32.8k Delete a directory in Go
+18.2k Golang : Example for RSA package functions
+21.6k Golang : Use TLS version 1.2 and enforce server security configuration over client
+8.7k Golang : Build and compile multiple source files
+7.7k Swift : Convert (cast) String to Float
+6.3k Golang : Totalize or add-up an array or slice example