版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本篇文档借鉴:https://blog.csdn.net/qq_24807077/article/details/79555030
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Text;
public class ReadText : MonoBehaviour {
StreamWriter writer;
StreamReader reader;
List<string> Allmytxt = new List<string>();
string _txtPath;
// Use this for initialization
void Start()
{
_txtPath = Application.dataPath + "/mytxt.txt";//txt文本存储在本项目工程路径
_txtPath = "D:\\MyTest\\mytxt.txt"; ;//txt文本存储在电脑的某个文件夹
//分别调用保存或读取方法
SaveText();
GetdataFromText();
}
//保存Txt文档
void SaveText()
{
FileInfo file = new FileInfo(_txtPath);
if (file.Exists)
{
file.Delete();
file.Refresh();
}
WriteIntoTxt("message");
}
//把获取的数据打印出来
void GetdataFromText()
{
Allmytxt = GetmytxtList();
for (int i = 0; i < Allmytxt.Count; i++)
{
Debug.LogError(Allmytxt.Count);
Debug.LogError(Allmytxt[i]);
}
}
//把所有的数据写入Txt文本中
public void WriteIntoTxt(string message)
{
FileInfo file = new FileInfo(_txtPath);
if (!file.Exists)
{
writer = file.CreateText();
}
else
{
writer = file.AppendText();
}
writer.WriteLine(message);
writer.Flush();
writer.Dispose();
writer.Close();
}
//从Txt读取数据 存储到列表中
public void ReadOutTxt()
{
Allmytxt.Clear();
reader = new StreamReader(_txtPath, Encoding.UTF8);
string text;
while ((text = reader.ReadLine()) != null)
{
Allmytxt.Add(text);
}
reader.Dispose();
reader.Close();
}
/// <summary>
/// 获取从列表读取数据之后的List
/// </summary>
/// <returns></returns>
public List<string> GetmytxtList()
{
ReadOutTxt();
return Allmytxt;
}
}