学习笔记,写到哪是哪。
接着上一篇,我们看看io/ioutil工具如何使用,简化文件操作。
读取文件
读取文件可以使用ReadAll方法或者ReadFile方法。
ReadAll方法样例代码如下
//读取文件ReadAll
func IoUtilRead1() {
_file, _e := os.Open("./test.txt")
if _e != nil {
fmt.Println(_e)
return
}
defer _file.Close()
_text, _err := ioutil.ReadAll(_file)
fmt.Println(_err)
fmt.Println(string(_text))
}
文件内容和执行结果如下
今天天气真好Process finished with the exit code 0
ReadFile方法样例代码如下
//读取文件ReadFile
func IoUtilRead2() {
_text, _err := ioutil.ReadFile("./test.txt")
fmt.Println(_err)
fmt.Println(string(_text))
}
执行结果如下
今天天气真好Process finished with the exit code 0
写文件
可以使用ioutil.WriteFile方法写文件。<