Sunday, 12 May 2019

Go Language: Read file line by line


Below function read a file and return array of strings.

func readFile(filePath string) []string {
         file, err := os.Open(filePath)

         if err != nil {
                  log.Fatal(err)
         }

         defer file.Close()

         scanner := bufio.NewScanner(file)

         result := []string{}

         for scanner.Scan() {
                  result = append(result, scanner.Text())
         }

         if err := scanner.Err(); err != nil {
                  log.Fatal(err)
         }
         return result
}

App.go
package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
)

func readFile(filePath string) []string {
	file, err := os.Open(filePath)

	if err != nil {
		log.Fatal(err)
	}

	defer file.Close()

	scanner := bufio.NewScanner(file)

	result := []string{}

	for scanner.Scan() {
		result = append(result, scanner.Text())
	}

	if err := scanner.Err(); err != nil {
		log.Fatal(err)
	}
	return result
}

func main() {
	filePath := "/Users/krishna/Downloads/Welcome.pdf"

	content := readFile(filePath)
	fmt.Println(content)
}



Previous                                                 Next                                                 Home

No comments:

Post a Comment