5.4 readfile to a string


package main

import "os"
import "bufio"

import "bytes"
import "fmt"
import "io/ioutil"

func main() {

	fmt.Println("### Read as reader ###")
	f, err := os.Open("temp/file.txt")
	if err != nil {
		panic(err)
	}
	defer f.Close()

	// Read the
	// file with reader
	wr := bytes.Buffer{}
	sc := bufio.NewScanner(f)
	for sc.Scan() {
		wr.WriteString(sc.Text())
	}
	fmt.Println(wr.String())

	fmt.Println("\n### ReadFile ###")
	// for smaller files
	fContent, err := ioutil.ReadFile("temp/file.txt")
	if err != nil {
		panic(err)
	}
	fmt.Println(string(fContent))

}

/*
### Read as reader ###
Lorem ipsum dolor sit amet, consectetur adipiscing elit.Mauris id pretium eros. Aliquam imperdiet mi ut elit faucibus porta.Donec facilisis nunc at risus dapibus elementum.

### ReadFile ###
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Mauris id pretium eros. Aliquam imperdiet mi ut elit faucibus porta.
Donec facilisis nunc at risus dapibus elementum.
*/

posted on 2018-03-22 00:51  cucy_to  阅读(116)  评论(0编辑  收藏  举报

导航