标签:line user kill defer editable odi users write data
package main
import (
"bufio"
"encoding/json"
"fmt"
"os"
)
type Monster struct {
Name string
Age int
Skill string
}
func (m *Monster) Store(path string) {
b, err := json.Marshal(m)
if err != nil {
return
}
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0666)
writer := bufio.NewWriter(f)
n, err := writer.WriteString(string(b))
fmt.Printf("共写入了%d个字节", n)
defer f.Close()
writer.Flush()
}
func (m *Monster) Restore(path string) {
f, _ := os.OpenFile(path, os.O_RDONLY, 0666)
reader := bufio.NewReader(f)
fileInfo, _ := os.Stat(path)
s := make([]byte, fileInfo.Size())
_, error := reader.Read(s)
//content, error := ioutil.ReadAll(f)
//fmt.Println(content)
fmt.Println(s)
if error != nil {
fmt.Print(error)
return
}
json.Unmarshal(s, &m)
defer f.Close()
}
func main() {
//monster := Monster{"绿巨人", 36, "变身"}
var monster2 Monster
path := "/Users/xiahualou/Public/OneDrive/GoDevelopment/src/gocode/project18/main/1.txt"
//monster.Store(path)
monster2.Restore(path)
fmt.Print(monster2)
标签:line user kill defer editable odi users write data
原文地址:https://www.cnblogs.com/hualou/p/12069895.html