Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read text file into string array (and write)

Tags:

go

The ability to read (and write) a text file into and out of a string array is I believe a fairly common requirement. It is also quite useful when starting with a language removing the need initially to access a database. Does one exist in Golang?
e.g.

func ReadLines(sFileName string, iMinLines int) ([]string, bool) { 

and

func WriteLines(saBuff[]string, sFilename string) (bool) {  

I would prefer to use an existing one rather than duplicate.

like image 423
brianoh Avatar asked May 04 '11 13:05

brianoh


People also ask

How do you read a text file and store it to an array in Java?

In Java, we can store the content of the file into an array either by reading the file using a scanner or bufferedReader or FileReader or by using readAllLines method.

How do you convert a text file to an array in Java?

All you need to do is read each line and store that into ArrayList, as shown in the following example: BufferedReader bufReader = new BufferedReader(new FileReader("file. txt")); ArrayList<String> listOfLines = new ArrayList<>(); String line = bufReader. readLine(); while (line !


2 Answers

As of Go1.1 release, there is a bufio.Scanner API that can easily read lines from a file. Consider the following example from above, rewritten with Scanner:

package main  import (     "bufio"     "fmt"     "log"     "os" )  // readLines reads a whole file into memory // and returns a slice of its lines. func readLines(path string) ([]string, error) {     file, err := os.Open(path)     if err != nil {         return nil, err     }     defer file.Close()      var lines []string     scanner := bufio.NewScanner(file)     for scanner.Scan() {         lines = append(lines, scanner.Text())     }     return lines, scanner.Err() }  // writeLines writes the lines to the given file. func writeLines(lines []string, path string) error {     file, err := os.Create(path)     if err != nil {         return err     }     defer file.Close()      w := bufio.NewWriter(file)     for _, line := range lines {         fmt.Fprintln(w, line)     }     return w.Flush() }  func main() {     lines, err := readLines("foo.in.txt")     if err != nil {         log.Fatalf("readLines: %s", err)     }     for i, line := range lines {         fmt.Println(i, line)     }      if err := writeLines(lines, "foo.out.txt"); err != nil {         log.Fatalf("writeLines: %s", err)     } } 
like image 99
Kyle Lemons Avatar answered Sep 19 '22 12:09

Kyle Lemons


Note: ioutil is deprecated as of Go 1.16.

If the file isn't too large, this can be done with the ioutil.ReadFile and strings.Split functions like so:

content, err := ioutil.ReadFile(filename) if err != nil {     //Do something } lines := strings.Split(string(content), "\n") 

You can read the documentation on ioutil and strings packages.

like image 22
yanatan16 Avatar answered Sep 21 '22 12:09

yanatan16