Go 读取文件

2021-06-04 09:51
245
0
package main

import (
   "bufio"
   "fmt"
   "io/ioutil"
   "log"
   "os"
)

func main() {
   //golang 按行读取文件

   file, err := os.Open("app-2019-06-01.log")
   if err != nil {
      log.Fatal(err)
   }
   defer file.Close()
   scanner := bufio.NewScanner(file)
   for scanner.Scan() {
      lineText := scanner.Text()
      fmt.Println(lineText)

   }

   //整个读取

   b, err := ioutil.ReadFile("app-2019-06-01.log") // just pass the file name
   if err != nil {
      fmt.Print(err)
   }

   str := string(b) // convert content to a 'string'

   fmt.Println(str) // print the content as a 'string'
}

全部评论