package main

import (
"fmt"
"io/ioutil"
"os"
) func main() {
filename := "a.txt"
//--------- create file ----------
file, err := os.Create(filename)
if err != nil {
fmt.Println(err)
}
defer file.Close() str := "你好,世界"
data := []byte(str) err = ioutil.WriteFile(filename, data, ) //--------- read file ------------
buf := make([]byte, )
n, err := file.Read(buf)
if err != nil {
fmt.Println(err)
}
fmt.Printf("------------method 1-------------\n%v\n", buf)
fmt.Printf("--> 读取长度:%v\n", n)
fmt.Printf("--> %v,\n", string(buf)) //------------ read file method 2 ---------
res, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Println(err)
}
fmt.Println("---------- method 2----------")
fmt.Println(string(res)) }

结果:

$ go run main.go
------------method -------------
[ ]
--> 读取长度:
--> 你好,世界,
---------- method ----------
你好,世界
05-28 22:19