文件的创建,写入,读取,需要使用流来操作。
示例代码如下:
- void Start ()
- {
- Createfile (Application.dataPath, "FileName", "TestInfo0");
- Createfile (Application.dataPath, "FileName", "TestInfo1");
- Createfile (Application.dataPath, "FileName", "TestInfo2");
- }
- //文件的创建,写入
- void Createfile (string path, string name, string info)
- {
- StreamWriter sw;//流信息
- FileInfo t = new FileInfo (path + "//" + name);
- if (!t.Exists) {//判断文件是否存在
- sw = t.CreateText ();//不存在,创建
- } else {
- sw = t.AppendText ();//存在,则打开
- }
- sw.WriteLine (info);//以行的形式写入信息
- sw.Close ();//关闭流
- sw.Dispose ();//销毁流
- }
下面是文件的读取实例:
- void Start ()
- {
- //读取文件
- ArrayList info = LoadFile (Application.dataPath, "FileName");
- foreach (string str in info) {//打印信息
- Debug.Log (str);
- }
- }
- ArrayList LoadFile (string path, string name)
- {
- StreamReader sr = null;//文件流
- try {
- //通过路径和文件名读取文件
- sr = File.OpenText (path + "//" + name);
- } catch (Exception ex) {
- return null;
- }
- string line;
- ArrayList arrlist = new ArrayList ();
- while ((line = sr.ReadLine ()) != null) {//读取每一行加入到ArrayList中
- arrlist.Add (line);
- }
- sr.Close ();
- sr.Dispose ();
- return arrlist;
- }