使用 ioutil 读取和写入文件
写一个简单的程序,写着 Hello World!
到 test.txt
,读取数据并打印出来。演示简单的文件 I / O 操作。
package main
import (
"fmt"
"io/ioutil"
)
func main() {
hello := []byte("Hello, world!")
// Write `Hello, world!` to test.txt that can read/written by user and read by others
err := ioutil.WriteFile("test.txt", hello, 0644)
if err != nil {
panic(err)
}
// Read test.txt
data, err := ioutil.ReadFile("test.txt")
if err != nil {
panic(err)
}
// Should output: `The file contains: Hello, world!`
fmt.Println("The file contains: " + string(data))
}