首页 > 解决方案 > 如何在运行时将文本文件从 Unity Asset 文件夹移动到 Android persistentDataPath?

问题描述

在我的项目中,我在资产文件夹中有我的文本文件,我想在运行时将文件移动或复制到 Android persistenceDatapath。

我的文本文件存储字节数据,所以我尝试读取所有字节并将其写回持久数据路径,然后我尝试从那里读取。但是数据并没有正常发送。

所以我决定在运行时移动或复制文件。它在编辑器中工作正常,但不能在 android 中工作。

FileInfo fi = new FileInfo(Path.Combine(Application.streamingAssetsPath + "/a.txt"));
fi.CopyTo(Path.Combine(Application.persistentDataPath, "a.txt"), true);

这条线在我的编辑器中工作正常,但在导出到 android 后它不起作用。

当我在 android 设备中尝试以下条件时,它没有执行

if(File.Exists(Path.Combine(Application.streamingAssetsPath + "/a.txt")))
            infotext.text = "PATH FIND IN THE RESOURCE FOLDER";

有人可以帮我解决这个问题吗?

标签: c#androidfileunity3d

解决方案


使用UnityWebRequestandDownloadHandlerFile将文件从 apk 复制到数据。

    string fileInData = Application.persistentDataPath + "/a.txt";
#if UNITY_ANDROID
    string fileInApk = Application.streamingAssetsPath + "/a.txt";
    if (!File.Exists(fileInData))
    {
        var request = UnityWebRequest.Get(fileInApk);
        var download = new DownloadHandlerFile(fileInData);
        request.downloadHandler = download;
        yield return request.SendWebRequest();
    }
#endif

推荐阅读