Go读写文件

Go序列化和反序列化

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)




posted @ 2019-12-19 20:09  离地最远的星  阅读(108)  评论(0编辑  收藏  举报