Unity开发对于文件操作有两种不同的类型:
1:只读取,这个类型也分为二进制资源读取与一般自身数据资源读取,一般的自身资源读取通常用于游戏数据的读取,放在Resource的文件夹里面,比如csv类型的关卡数据等等,这种类型不会涉及到写入的问题,只用用Resource.Load的方式就可以了。而二进制资源的读取是要放在StreamAssets的文件夹里面,详细读取方式可以参照我另外一篇文章。
2:读写,这种可以用于玩家信息的存放等等,以下就提供一下基本操作的源码:
private static string RootPath
{
get{
if(Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.Android)
{
return Application.persistentDataPath + "/";
}
else if(Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.OSXEditor)
{
///*如果是电脑的编辑模式,先放在项目外面*/
return Application.dataPath.Replace ("Assets", "");
}
else
{
return Application.dataPath + "/";
}
}
}
/// <summary>
/// 写文件操作
/// 指定路径文件不存在会被创建
/// </summary>
/// <param name="path">文件路径(包含Application.persistentDataPath).</param>
/// <param name="name">文件名.</param>
/// <param name="info">写入内容.</param>
public static void createORwriteFile (string fileName, string info)
{
FileStream fs = new FileStream (RootPath + fileName, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter (fs);
fs.SetLength (0); ///*清空文件*/
sw.WriteLine (info);
sw.Close ();
sw.Dispose ();
}
/// <summary>
/// 读取文件内容 仅读取第一行
/// </summary>
/// <returns>The file.</returns>
/// <param name="path">Path.</param>
/// <param name="name">Name.</param>
public static string ReadFile (string fileName)
{
string fileContent;
StreamReader sr = null;
try{
sr = File.OpenText(RootPath + fileName);
}
catch(Exception e){
return null;
}
while ((fileContent = sr.ReadLine()) != null) {
break;
}
sr.Close ();
sr.Dispose ();
return fileContent;
}
public static bool IsFileExists(string fileName)
{
return File.Exists(RootPath + fileName);
}
public static void DelectFile(string fileName)
{
File.Delete(RootPath + fileName);
}