如何在 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** 之外的其他名称,则代码将产生错误。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例 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

更新于: 2022年2月21日

9K+ 浏览量

启动您的 职业生涯

通过完成课程获得认证

开始学习
广告