Unity下關於C#的檔案讀寫一(基於TXT的簡單讀寫)
阿新 • • 發佈:2018-12-26
Unity下關於C#的檔案讀寫(基於TXT和LitJson)
NOTE (基本認識):其實.txt,.xml,.json這類檔案都屬於文字檔案,類似的還有.lrc歌詞檔案,.ini配置檔案,.reg登錄檔檔案等等,這類檔案所儲存的內容都是文字(即為字串),只是各自有它們自己的格式,便於某些時候專用識別,所以讀取txt文字是最基礎的文字解析。
基本的txt讀取
靜態內部讀取txt文字:
最簡單的方式,建立TextAsset,直接把文字檔案拖上去,就可以用了,
public TextAsset TxtFile;
print(TxtFile.text);
這是直接獲取文字,也就是string型別的字串。
Note
動態內部讀取文字:
把txt檔案放在resources資料夾,利用Resources.Load載入:
public TextAsset TxtFile;
private string Mytxt;
void Start()
{
Mytxt=(TextAsset)Resources.Load("MyTest").text;
print(Mytxt);
}
下面是一些寫好的案例:
//返回整個文字字串
string[] ReadAllFile(string FileName)
{
string [] strs;
return strs = File.ReadAllLines(FileName);
}
//讀取文字某一行字串
string ReadALine(string FileName,int linenumber) // 引數1:開啟的檔案(路徑+檔案命),引數2:讀取的行數
{
string[] strs = File.ReadAllLines(FileName);
if(linenumber==0)
{
return "0";
}
else
{
return strs[linenumber - 1];
}
}
/*重寫TXT文件*/
void WriteAllFile(string FileName,string txt)// 引數1:開啟的檔案(路徑+檔案命),引數2:重寫所有文件的字串
{
string[] str = txt.Split(';');
File.WriteAllLines(FileName,str);
}
//在TXT文件中插入行
void WriteALine(string FileName, string txt,int lineNumber)// 引數1:開啟的檔案(路徑+檔案命),引數2:重寫某行的字串,引數3,插入的行數
{
string[] str = File.ReadAllLines(FileName);
int strLinesLength = str.Length;
string[] strNew = new string[strLinesLength + 1];
bool haveAddLine = false;//是否已經插入行
for(int i=0;i< strLinesLength + 1;++i )
{
if(i==lineNumber-1) //到達插入行,插入並跳過此次下面的新增
{
strNew[i] = txt;
haveAddLine = true;
}
else if(!haveAddLine)//還沒插入新建行時
{
strNew[i] = str[i];
}
else//插入之後
{
strNew[i] = str[i - 1];
}
}
File.WriteAllLines(FileName, strNew);
}