unity3d开发对Txt文件的读写
1.引入库
本地的txt文件的读取,需要引入System.IO
using System.IO;
2.读入数据
从StreamingAsset文件夹读取数据
public static string ReadFileFromStreamingAsset(string File_Name)
{
string File_Path;
if (Application.platform == RuntimePlatform.Android)
File_Path = "jar:file://" + Application.dataPath + "!/assets/" + File_Name;
else
File_Path = Application.dataPath + "/StreamingAssets/" + File_Name;
WWW www = new WWW(File_Path);
while (!www.isDone) { }
if (www.error == null) return www.text;
else return www.error;
}
这里需要注意的是平台不同,读取文件的路径需要做区分
从PersistentDataPath读取数据,需要先从StreamingAssets中拷贝一份
public static void CopyFileFromStreamingAsset(string File_Name)
{
string From_Path;
if (Application.platform == RuntimePlatform.Android)
From_Path = "jar:file://" + Application.dataPath + "!/assets/" + File_Name;
else
From_Path = Application.dataPath + "/StreamingAssets/" + File_Name;
string To_Path = Application.persistentDataPath + "/" + File_Name;
WWW www = new WWW(From_Path);
while (!www.isDone) { }
if (www.error == null)
File.WriteAllBytes(To_Path, www.bytes);
}
public static string[] ReadFileLines(string file_name)//读取
{
string path = Application.persistentDataPath + "/" + file_name;
if (!File.Exists(path)) { CopyFileFromStreamingAsset(file_name); };
return File.ReadAllLines(path);
}
3.写入数据
游戏中产生的变更文件或游戏中生成的新文件存入PersistentDataPath
public static void CreateFileToPersistenDataPath(string File_Name, string Str_info)
{
StreamWriter sw;
FileInfo t = new FileInfo(Application.persistentDataPath + "/" + File_Name);
if (!t.Exists)
{
sw = t.CreateText();
}
else
{
t.Delete();
t.Refresh();
sw = t.AppendText();
}
sw.Write(Str_info);
sw.Dispose();
sw.Close();
}