unity, write/read txt file
在Assets下新建文件夹StreamingAssets。然后下面代码可在其中生成test.txt文件,并读写:
using UnityEngine;
using System.Collections;
using System.IO;
using System.Collections.Generic;
public class readAndWriteFile : MonoBehaviour {
void Start(){
test ();
}
void test(){
//write file
{
List<string> strListToWrite = new List<string> ();
strListToWrite.Add ("hellow 1");
strListToWrite.Add ("lady 4");
strListToWrite.Add ("i love you 5");
writeToFile ("test.txt", false, strListToWrite);
}
//read file
List<List<string> > strMat=null;
{
strMat=readFromFileToStrMat("test.txt");
}
//print reading result
{
printStrMat(strMat);
}
}
public void writeToFile(string fileNameWithExt,bool isAppend,List<string> strList){
string path=Application.streamingAssetsPath+"/"+fileNameWithExt;
Debug.Log (path);
StreamWriter sw = new StreamWriter(path,isAppend);
int strCount = strList.Count;
for (int i=0; i<strCount; i++) {
sw.WriteLine (strList[i]);
}
sw.Close ();
}
public List<string> readFromFileToStrList(string fileNameWithExt){
List<string> strList = new List<string> ();
StreamReader sr = new StreamReader (Application.streamingAssetsPath+"/"+fileNameWithExt);
string line = sr.ReadLine ();
while (line!=null) {
strList.Add(line);
line = sr.ReadLine ();
}
sr.Close ();
return strList;
}
public List<List<string> > readFromFileToStrMat(string fileNameWithExt){
List<string> strList = readFromFileToStrList (fileNameWithExt);
List<List<string> > strMat = strListToSubStrMat (strList);
return strMat;
}
public void printStrList(List<string> strList){
int strCount = strList.Count;
for (int i=0; i<strCount; i++) {
print(strList[i]);
}
}
public void printStrMat(List<List<string> > strMat){
int nRow = strMat.Count;
for (int i=0; i<nRow; i++) {
print ("row"+i+":");
int nCol=strMat[i].Count;
for(int j=0;j<nCol;j++){
print (strMat[i][j]);
}
}
}
public List<string> strToSubStrList(string str){
string[] subStrArr=str.Split (new char[]{' ','\n'});
List<string> subStrList = new List<string> ();
int subStrCount = subStrArr.Length;
for (int i=0; i<subStrCount; i++) {
string subStr=subStrArr[i];
if(subStr.Length!=0){
subStrList.Add(subStrArr[i]);
}
}
return subStrList;
}
public List<List<string> > strListToSubStrMat(List<string> strList){
List<List<string> > subStrMat=new List<List<string> >();
int strCount = strList.Count;
for (int i=0; i<strCount; i++) {
List<string> subStrList=strToSubStrList(strList[i]);
subStrMat.Add(subStrList);
}//got subStrMat
return subStrMat;
}
}
另外一种读取txt文件的方法:http://www.cnblogs.com/wantnon/p/4605415.html