Go語言程式讀取現有檔案的全部文字


在這篇Go語言文章中,我們將分別使用`io/ioutil`包中的`ReadFile`函式,`bufio`包中的`NewScanner`函式以及前一個包中的`NewReader`函式來讀取現有檔案的全部文字。

語法

bufio.NewReader()

此函式屬於Go的`bufio`包。此函式的主要目標是以較大的塊而不是逐行讀取資料,並將其儲存在緩衝區中。`io.reader`和緩衝區大小作為引數傳遞給此函式。

os.Open()

此函式是`os`包的一部分。它用於開啟檔案以進行讀取。它接受一個輸入,即要開啟的檔名。

ioutil.ReadFile()

此函式在`ioutil`包中可用,用於讀取以檔名作為函式輸入的檔案內容。

bufio.NewScanner()

此函式是`bufio`包的一部分。它用於建立一個掃描器物件以讀取檔案中的資料。

演算法

  • 在程式中匯入所需的包

  • 建立一個主函式

  • 使用內建函式讀取檔案內容

  • 如果內容未正確讀取,則列印錯誤

示例1

在這個例子中,我們將編寫一個Go語言程式,使用`ioutil`包中的`ReadFile()`函式讀取現有檔案的全部文字。此函式讀取檔案的全部內容並將其作為位元組切片返回。

package main

import (
   "fmt"
   "io/ioutil"
)

func main() {
   data, err := ioutil.ReadFile("file.txt")
   if err != nil {
      fmt.Println("Error reading file:", err)
      return
   }
   fmt.Println(string(data))
}

輸出

The dictionary says it was Thomas Edison who put hello into common usage. He urged the people who used his phone to say "hello" when answering.
His rival, Alexander Graham Bell, thought the better word was "ahoy."

示例2

在這個例子中,我們將編寫一個Go語言程式,使用`os`和`bufio`包中的函式讀取現有檔案的全部文字。

package main

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

func main() {
   file, err := os.Open("file.txt")
   if err != nil {
      fmt.Println("Error opening file:", err)
      return
   }
   defer file.Close()

   scanner := bufio.NewScanner(file)
   for scanner.Scan() {
      fmt.Println(scanner.Text())
   }

   if err := scanner.Err(); err != nil {
      fmt.Println("Error reading file:", err)
   }
}

輸出

The dictionary says it was Thomas Edison who put hello into common usage. He urged the people who used his phone to say "hello" when answering.
His rival, Alexander Graham Bell, thought the better word was "ahoy."

示例3

在這個例子中,我們將編寫一個Go語言程式,使用`NewReader`函式讀取檔案的全部文字。此方法比以前的方法提供對讀取過程的更多控制。

package main

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

func main() {
   file, err := os.Open("file.txt")
   if err != nil {
      fmt.Println("Error opening file:", err)
      return
   }
   defer file.Close()

   reader := bufio.NewReader(file)
   data, err := reader.ReadString('\n')
   if err != nil {
      fmt.Println("Error reading file:", err)
      return
   }
   fmt.Println(data)
}

輸出

The dictionary says it was Thomas Edison who put hello into common usage. He urged the people who used his phone to say "hello" when answering.
His rival, Alexander Graham Bell, thought the better word was "ahoy."

結論

我們已經成功編譯並執行了一個Go語言程式,該程式讀取現有檔案的全部文字以及示例。在第一個示例中,我們使用`ReadFile()`函式,而在第二個和第三個示例中,我們分別使用`NewScanner()`和`NewReader()`函式來實現結果。

更新於:2023年5月3日

455 次瀏覽

啟動您的職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.