文件管理类: FileManager.cs
using System; using UnityEngine; using System.Collections; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace FrameWork { public class FileManager : Singleton<FileManager> { #if UNITY_EDITOR public static string persistPath = UnityEngine.Application.persistentDataPath; //persistPath = string.Format(@"Assets/StreamingAssets/{0}", fileName); #elif UNITY_ANDROID public static string persistPath = "jar:file://" + Application.dataPath + "!/assets"; #elif UNITY_IOS public static string persistPath = Application.dataPath + "/Raw"; #else public static string persistPath = UnityEngine.Application.persistentDataPath; //persistPath = Application.dataPath + "/StreamingAssets/" + fileName; //UNITY_WINRT, UNITY_WP8 in this path #endif private FileManager() { } public static string getAppPath(string fileName) { return string.Format(@"{0}/{1}", persistPath, fileName); //安卓可能需要www去load // WWW loadDb = new WWW("jar:file://" + Application.dataPath + "!/assets/" + LOCAL_DB_NAME); // while (!loadDb.isDone) { } // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, // File.WriteAllBytes(filepath, loadDb.bytes); } //写入文件 public static void writeFile(string fileName, byte[] datas) { string persistPath = getAppPath(fileName); BinaryFormatter bf = new BinaryFormatter(); using (FileStream fs = new FileStream(persistPath, FileMode.Create, FileAccess.Write)) { bf.Serialize(fs, datas); } } public static bool isExists(string fileName) { string persistPath = getAppPath(fileName); FileInfo file = new FileInfo(fileName); if (file.Exists) { return true; } return false; } //读取文件 public static byte[] readFile(string fileName) { string persistPath = getAppPath(fileName); BinaryFormatter bf = new BinaryFormatter(); FileInfo file = new FileInfo(persistPath); Debug.Log(persistPath); if (file.Exists) { Debug.Log("find file successfully!!"); using (FileStream fs = new FileStream(persistPath, FileMode.Open, FileAccess.Read)) { byte[] data = (Byte[])bf.Deserialize(fs); return data; } } return null; } /// 清空指定的文件夹,但不删除文件夹 /// </summary> /// <param name="dir"></param> public static void DeleteFolder(string dir) { foreach (string d in Directory.GetFileSystemEntries(dir)) { if (File.Exists(d)) { FileInfo fi = new FileInfo(d); if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1) fi.Attributes = FileAttributes.Normal; File.Delete(d);//直接删除其中的文件 } else { DirectoryInfo d1 = new DirectoryInfo(d); if (d1.GetFiles().Length != 0) { DeleteFolder(d1.FullName);////递归删除子文件夹 } Directory.Delete(d); } } } } }测试代码片段
public void test() { byte[] writeContent = Encoding.Default.GetBytes("hello word"); FileManager.writeFile("test.txt", writeContent); byte[] readContent = FileManager.readFile("test.txt"); }