Unity3D操作數(shù)據(jù)之Txt文檔操作(創(chuàng)建、讀取、寫入、修改)
一、前言
其實(shí)讀取Txt文檔非常簡(jiǎn)單、也不需要導(dǎo)入插件,僅需引入相應(yīng)的命名空間即可。
- 命名空間:using System.IO
- 要注意的一點(diǎn)是,文檔格式設(shè)置為UTF-8,不然中文可能顯示不太正確。
二、創(chuàng)建
- 使用寫入語句會(huì)自動(dòng)創(chuàng)建對(duì)應(yīng)的文檔
- 使用FileStream創(chuàng)建
//先判斷是否存在,再創(chuàng)建
if (!File.Exists(Application.dataPath + "/TextRead.txt"))
{
FileStream fileStream = new FileStream(Application.dataPath + "/TextRead.txt", FileMode.OpenOrCreate);
fileStream.Close();
}
三、寫入
寫入主要有兩種方式:File.WriteAllText() 函數(shù)及 ReadWriteLines() 函數(shù)
-
File.WriteAllText()
- 將整個(gè)文本保存到文檔中。
string path = Application.dataPath + "/TextRead.txt";
File.WriteAllText(path, "將整個(gè)文本保存到文檔中");
-
ReadWriteLines()
- 將一個(gè)string數(shù)組保存到文檔中。
- 數(shù)組多長(zhǎng)就會(huì)寫幾行(一個(gè)索引一行內(nèi)容)
string path = Application.dataPath + "/TextRead.txt";
string[] test = { "測(cè)試數(shù)據(jù)1", "測(cè)試數(shù)據(jù)2", "測(cè)試數(shù)據(jù)3" };
File.WriteAllLines(path, test);
運(yùn)行結(jié)果:
四、讀取
讀取主要有兩種函數(shù):File.ReadAllText() 函數(shù)及 ReadAllLines() 函數(shù)文章來源:http://www.zghlxwxcb.cn/news/detail-782646.html
-
ReadAllText()
- 把文檔所有內(nèi)容讀取下來:
- 返回值:字符串
string textTxt = File.ReadAllText(Application.dataPath + "/TextRead.txt");
-
ReadAllLines()
- 將這個(gè)文檔按照一行一行進(jìn)行全部讀?。?/li>
- 返回值:字符串?dāng)?shù)組
string[] textTxt = File.ReadAllLines(Application.dataPath + "/TextRead.txt");
for (int i = 0; i < textTxt.Length; i++)
{
Debug.Log(textTxt[i]);
}
讀取結(jié)果:
工程文件下載地址:
CSDN:https://download.csdn.net/download/Xz616/87418985
百度網(wǎng)盤:https://pan.baidu.com/s/1LuLzK-vqATphsYNS6TOy_w?pwd=4wqd文章來源地址http://www.zghlxwxcb.cn/news/detail-782646.html
到了這里,關(guān)于Unity3D操作數(shù)據(jù)之Txt文檔操作(創(chuàng)建、讀取、寫入、修改)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!