在streamingAssetsPath上读取和写入文件 [英] Read and Write file on streamingAssetsPath
问题描述
这就是我在android中读取文本文件的方式.
This is how i read my textfile in 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读取文本文件的方式.
and this is how i read my textfile from 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
现在我的问题是我不知道如何在移动设备上写入文件,因为我是在独立机上这样做的
Now my problem is that i don't know how to write the file on mobile cause i do it like this on the standalone
#if UNITY_STANDALONE
StreamWriter writer = new StreamWriter(path, false);
writer.WriteLine(json);
writer.Close();
#endif
帮助任何人
这是我需要获取的我的streamingasset文件夹中的json文件
This is the json file that it is in my streamingasset folder that i need to get
推荐答案
现在我的问题是我不知道如何在移动设备上写入文件 因为我是在独立机上这样做的
Now my problem is that i don't know how to write the file on mobile cause I do it like this on the standalone
您无法保存到此位置. 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"文件:
Let's load your "datacenter.json" file from your screenshot:
void Start()
{
StartCoroutine(loadStreamingAsset("datacenter.json"));
}
保存数据:
Saving Data:
保存在所有平台上均可使用的数据的路径为Application.persistentDataPath
.在将数据保存到该路径之前,请确保在该路径内创建一个文件夹.您问题中的StreamReader
可用于读取或写入此路径.
The path to save a data that works on all platform is Application.persistentDataPath
. Make sure to create a folder inside that path before saving data to it. The StreamReader
in your question can be used to read or write to this path.
保存到Application.persistentDataPath
路径:
使用File.WriteAllBytes
从Application.persistentDataPath
路径读取
使用File.ReadAllBytes
.
请参见 此 帖子中提供了有关如何在Unity中保存数据的完整示例.
See this post for a complete example of how to save data in Unity.
这篇关于在streamingAssetsPath上读取和写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!