提前建一个文件文本helloworld.txt,现在可以在Go程序中使用绝对文件路径将helloworld整个文件读取。代码中使用到 ioutol包中的 ReadFile函数。在Go语言标准库文档中它的用法是:
func ReadFile(filename string) ([]byte, error)
说明:ReadFile 从filename指定的文件中读取数据并返回文件的内容。成功的调用返回的err为nil而非EOF。因为本函数定义为读取整个文件,它不会将读取返回的EOF视为应报告的错误。
helloworld文本中的内容:
代码如下:
package main
import (
"fmt"
"io/ioutil"
)
func main() {
data, err := ioutil.ReadFile("/helloworld.txt")
if err != nil {
fmt.Println("获取失败", err)
return
}
fmt.Println("文本内容为:", string(data))
}
运行结果:
参考