首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在streamingAssetsPath上读取和写入文件?

在streamingAssetsPath上读取和写入文件?
EN

Stack Overflow用户
提问于 2018-06-14 09:55:59
回答 2查看 0关注 0票数 0

这是我在android中读取我的文本文件的方式。

代码语言:javascript
复制
#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读取我的文本文件。

代码语言:javascript
复制
#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

现在我的问题是,我不知道如何在移动设备上编写文件,因为我在独立设备上这样做

代码语言:javascript
复制
#if UNITY_STANDALONE
        StreamWriter writer = new StreamWriter(path, false);
        writer.WriteLine(json);
        writer.Close();
 #endif

这个
这个

这是我需要获取的在我的streamingasset文件夹中的json文件

EN

回答 2

Stack Overflow用户

发布于 2018-06-14 18:33:50

你无法保存到此位置Application.streamingAssetsPath是只读的。编辑器是否工作并不重要。它是只读的,不能用于加载数据

在这里输入图像描述
在这里输入图像描述

从StreamingAssets读取数据

代码语言:javascript
复制
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”文件:

代码语言:javascript
复制
void Start()
{
    StartCoroutine(loadStreamingAsset("datacenter.json"));
}

保存数据

保存可在所有平台上工作的数据的路径是Application.persistentDataPath。确保在保存数据之前在该路径中创建一个文件夹。在StreamReader你的问题中可以用来读取或写入该路径。

保存到Application.persistentDataPath路径:

使用 File.WriteAllBytes

Application.persistentDataPath路径中读取

使用File.ReadAllBytes

票数 0
EN

Stack Overflow用户

发布于 2018-06-14 19:48:27

代码语言:txt
复制
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);
    }

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100005392

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档