文件的读写

package main

import (
"bytes"
"fmt"
"io/ioutil"
"os"
"strings"
)
//读取文件
func ReadFile() (c string){
content, err := ioutil.ReadFile("ItemInfoRow.cpp")
if err != nil {
fmt.Println("read file err ", err)
return
}
fmt.Println(string(content))
return string(content)
}
//写文件
//拿到了ReadFile返回的字符串。
func WriteFile(content string) {
writeFile := "ItemInfoRow.json"
fileto, _ := os.OpenFile(writeFile, os.O_WRONLY, 0666)
defer fileto.Close()
var str string
var buffer bytes.Buffer
line := strings.Split(content, "\n")
for _, s := range line {
if strings.Contains(s,"{") {
buffer.WriteString("{")
}else if strings.Contains(s, "😊{
strRep := strings.Replace(s, ": ", "":"", -1)
strRep = fmt.Sprintf(""%s",", strRep)
buffer.WriteString(strRep)
}else if strings.Contains(s, "}") {
buffer.WriteString("}\n")
}
}
str = buffer.String()
str = strings.Replace(str, ",}", "}", -1)
str = strings.Replace(str, " ", "", -1)
res,error :=fileto.WriteString(string(str))
if error != nil {
fmt.Println("write file err ", error)
return
}
if res == 1002 {
fmt.Println("write success")
return
}
}

func main() {
var c string = ReadFile()
WriteFile(c)
}

posted @ 2021-06-22 17:07  dldream  阅读(60)  评论(0)    收藏  举报