沙盒文件的存储与读取

来源:互联网 发布:企管家软件怎么样 编辑:程序博客网 时间:2024/05/18 02:01
using System.Collections;using System.Collections.Generic;using UnityEngine;using System.IO;//引用命名空间public class ReadData : MonoBehaviour {    public BoolLevel leveBl;// BoolLevel为一个结构,leveBl用于存储Json解析出来的数据,并供unity使用,最后存入沙盒中void Start () {        //读取沙盒文件数据        read("LevelBL2.txt");}    void Update() {        if (Input.GetKeyDown(KeyCode.A)) {        //将数据存储在沙盒文件中            stroeData("LevelBL2.txt");        }        }    //读取沙盒文件 fileName为文件名    void read(string fileName) {        //沙盒文件路径        string sbPath = Application.persistentDataPath + fileName;        //如果沙盒存在文件        if (File.Exists(sbPath))        {            //打开流文件            FileStream file = new FileStream(sbPath,FileMode.Open);            //读取数据            StreamReader red = new StreamReader(file);            string data = red.ReadToEnd();            //将数据解析 存入leveBl            leveBl = JsonUtility.FromJson<BoolLevel>(data);            //关闭文件            red.Close();        }        //如果沙盒不存在文件 从unity StreamingAssets流文件中复制到沙盒中        else        {            //unity StreamingAssets文件路径            string oldPath=Application.dataPath+"/StreamingAssets/"+fileName;            //将文件复制到沙盒中            File.Copy(oldPath,sbPath);            print("Copyed");            //读取数据            FileStream file = new FileStream(sbPath, FileMode.Open);            StreamReader red = new StreamReader(file);            string data = red.ReadToEnd();            leveBl = JsonUtility.FromJson<BoolLevel>(data);            red.Close();        }    }    //存储沙盒文件    void stroeData(string fileName)    {              //沙盒文件路径             string sbPath = Application.persistentDataPath + fileName;             //创建一个新的文件将之前文件的替换(FileMode.Create)  ,使用 FileMode.Open只能实现部分数据内容覆盖,会报错            //也就是在文件更新数据之前 必须将文件里面的内容清空,再存入数据,由于没有Clear()方法,就使用替换文件的形式             FileStream file = new FileStream(sbPath, FileMode.Create);             StreamWriter write = new StreamWriter(file);             //将leveBl编译成JSon然后存入沙盒文件中             write.Write(JsonUtility.ToJson(leveBl));             write.Close();             file.Close();             print("stroed");         }        }

原创粉丝点击