在streamingAssetsPath上读写文件
这是我在android中读取我的文本文件的方式。
#if UNITY_ANDROID string full_path = string.Format("{0}/{1}",Application.streamingAssetsPath, path_with_extention_under_streaming_assets_folder); // Android only use WWW to read file WWW reader = new WWW(full_path); while (!reader.isDone){} json = reader.text; // PK Debug 2017.12.11 Debug.Log(json); #endif
这就是我从pc上读取我的文本文件的方法。
#if UNITY_STANDALONE string full_path = string.Format("{0}/{1}", Application.streamingAssetsPath, path_with_extention_under_streaming_assets_folder); StreamReader reader = new StreamReader(full_path); json = reader.ReadToEnd().Trim(); reader.Close(); #endif
现在我的问题是我不知道如何在移动设备上编写文件因为我在独立版上这样做
#if UNITY_STANDALONE StreamWriter writer = new StreamWriter(path, false); writer.WriteLine(json); writer.Close(); #endif
帮助任何人
更新的问题
这是我需要获取的在我的streamingasset文件夹中的json文件
现在我的问题是我不知道如何在移动设备上编写文件,因为我在独立版上这样做
您无法保存到此位置 。 Application.streamingAssetsPath
是只读的。 它是否适用于编辑器并不重要。 它是只读的,不能用于加载数据 。
从StreamingAssets读取数据 :
IEnumerator loadStreamingAsset(string fileName) { string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, fileName); string result; if (filePath.Contains("://") || filePath.Contains(":///")) { WWW www = new WWW(filePath); yield return www; result = www.text; } else { result = System.IO.File.ReadAllText(filePath); } Debug.Log("Loaded file: " + result); }
用法 :
让我们从你的截图中加载你的“datacenter.json”文件:
void Start() { StartCoroutine(loadStreamingAsset("datacenter.json")); }
保存数据 :
保存适用于所有平台的数据的路径是Application.persistentDataPath
。 确保在将数据保存到该路径之前在该路径中创建一个文件夹。 您问题中的StreamReader
可用于读取或写入此路径。
保存到Application.persistentDataPath
路径:
使用File.WriteAllBytes
从Application.persistentDataPath
路径读取
使用File.ReadAllBytes
。
有关如何在Unity中保存数据的完整示例,请参阅此文章。
这是我没有WWW
类的方式(适用于Android和iOS),希望它有用
public void WriteDataToFile(string jsonString) { if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } if (!File.Exists(filePath)) { File.Create(filePath).Close(); File.WriteAllText(filePath, jsonString); } else { File.WriteAllText(filePath, jsonString); } }