如何在 Golang 中將檔案讀取到字串中?
要將檔案讀取到字串中,我們需要使用 Go 標準庫提供的 io/ioutil 包。
在 **io/ioutil** 包中,有一個名為 **ReadFile()** 的函式,用於開啟檔案並將其內容轉換為位元組切片,如果由於某種原因無法執行此操作,則也會返回錯誤。
以下是 **ReadLine()** 函式的語法。
func ReadFile(filename string) ([]byte, error)
需要注意的是,如果上述函式成功呼叫,則會返回 **err == nil**,而不是 **err == EOF**。這是因為上述函式讀取整個檔案,它不會將來自 Read 的 EOF 視為錯誤。
我們將得到一個位元組切片,即 **[]byte**,而不是字串作為結果,要將其轉換為字串,我們需要進行基本型別轉換。
首先,讓我們考慮一個名為 **gocode.txt** 的檔案,其中包含以下內容。
This file contains some random text.
現在,讓我們看看我們將開啟此檔案並將其轉換為字串的程式碼。
示例 1
請考慮以下所示的程式碼。
package main
import (
"fmt"
"io/ioutil"
"log"
)
func main() {
fileContent, err := ioutil.ReadFile("gocode.txt")
if err != nil {
log.Fatal(err)
}
// Convert []byte to string
text := string(fileContent)
fmt.Println(text)
}輸出
如果我們在上述程式碼上執行命令 **go run main.go**,則將在終端中獲得以下輸出。
This file contains some random text.
如果由於某種原因,我們將檔名更改為除 **gocode.txt** 之外的其他名稱,則程式碼將產生錯誤。
示例 2
請考慮以下所示的程式碼。
package main
import (
"fmt"
"io/ioutil"
"log"
)
func main() {
fileContent, err := ioutil.ReadFile("gocode.txt")
if err != nil {
log.Fatal(err)
}
// Convert []byte to string
text := string(fileContent)
fmt.Println(text)
}輸出
如果我們在上述程式碼上執行命令 **go run main.go**,則將在終端中獲得以下輸出。
2021/10/11 12:05:46 open gocode.txt: no such file or directory exit status 1
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP