unity学习笔记——读写TXT
先直接贴代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;
public class ReadTxtManager : MonoBehaviour
{
private string path = "people";
public List<People> peopleList = new List<People>();
void Awake()
{
ReadTxt();
WriteTxt();
ReadTxt();
}
void ReadTxt()
{
//1
TextAsset txt = Resources.Load<TextAsset>(path);//比较简单易懂,适合于只读TXT
if (txt != null)
{
string[] allLine = txt.text.Split('\n');//换行分割每行信息,取到的全部文本在txt.text里
}
//2
FileInfo info = new FileInfo(Application.dataPath + "/Resources/" + path + ".txt");
if (info.Exists)
{
StreamReader reader = info.OpenText();//一般配合写入使用
string text = reader.ReadToEnd(); //取到的全部文本在reader.ReadToEnd()里,当然也可以使用reader.ReadLine()一行一行取
Debug.Log(text);
string[] allLines = text.Split('\n');//换行分割每行信息
peopleList.Clear();
for (int i = 1; i < allLines.Length; i++)//从第一行开始,第0行是各列标题
{
if (String.IsNullOrEmpty(allLines[i]))
{
continue;//忽略空白行
}
string[] line = allLines[i].Split('\t');//制表符分割每项信息
People peo = new People();
peo.id = int.Parse(line[0]);
peo.name = line[1];
peo.age = int.Parse(line[2]);
peo.score = int.Parse(line[3]);
peopleList.Add(peo);//存入列表中
}
reader.Dispose();
reader.Close();//记得在读写后调用关闭,否则会破坏共享
}
}
void WriteTxt()
{
FileInfo info = new FileInfo(Application.dataPath + "/Resources/" + path + ".txt");
StreamWriter writer = null;
if (info.Exists)
{
writer = info.AppendText();
}
else
{
writer = info.CreateText();//路径不存在则新创建一个TXT
}
string line = "5\tddddd\t20\t88";
writer.WriteLine(line);//写入数据
writer.Flush();
writer.Dispose();
writer.Close();//关闭
}
}
[Serializable]
public class People
{
public int id;
public string name;
public int age;
public int score;
}
其中FileInfo StreamWriter 等需要引入System.IO;
TXT表,末尾留一行用来保持格式。
写入后再读取的数据,可以看到已经写入成功了。