unity 读取安卓的streamingAssets里的配置文件

首先,安卓的streamingAssets是不在硬盘目录里的,直接读是读不到的,所以直接Application.StreamingAssets+"/文件名"是不行的,因为原本的streamingAssets里的文件都被打包到了jar包里,jar是一个压缩包,你可以直接用解压文件解压,在一个叫assets的文件里就能看到原本的文件

我们不能直接通过访问路径的方式获取streamingassets文件里的内容,但是我们可以使用www类读取其中的内容,并且复制到Applicaiton.persistentDataPath路径下,这个路径是Unity提供的安卓下可读可写的路径,但是只有在安装APK后才会出现,所以我们不能在工程中自己创建一个这个文件夹

复制streamingAssets中的内容到persistentDataPath并存储到本地词典,并获取值的具体代码如下

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class CommoneData
{
    
    
    /// <summary>
    /// 配置文件的名字
    /// </summary>
    private static string configName = "/Config.txt";
    /// <summary>
    /// 盛放配置文件的字典,在安卓不能直接读取ini,我们用txt
    /// </summary>
    private static Dictionary<string,string> dic = new Dictionary<string,string>();

    /// <summary>
    /// 获取配置
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public static string GetConfig(string key)
    {
    
    
        //如果持久化目录下没有配置文件,先从streamingAssets里复制一份到持久化目录
        if (!File.Exists(Application.persistentDataPath + configName))
        {
    
    
            WWW loadWWW = new WWW(Application.streamingAssetsPath + configName);
            while (!loadWWW.isDone)
            {
    
    

            }
            File.WriteAllBytes(Application.persistentDataPath + configName, loadWWW.bytes); 
        }

        //如果这个字典里没有键值对,先所有的读取键值对
        if (dic.Keys.Count == 0)
        {
    
    
            //读取所有的配置,并拆解成字典
            string[] allLines = File.ReadAllLines(Application.persistentDataPath + configName);
            for (int i = 0; i < allLines.Length; i++)
            {
    
    
                string[] temp = allLines[i].Split('=');
                dic.Add(temp[0].Trim(), temp[1].Trim());
            }
        }

        //根据键查找值
        try
        {
    
    
            return dic[key];
        }
        catch
        {
    
    
            Debug.LogError("字典中没有键:" + key);
            return "";
        }
    }

}

然后你就可以像读取streamingAssets一样,读取persistentDataPath里的内容了

额外注意
1 untiy打包安卓的安装目录
2 安卓不能用ini配置文件

猜你喜欢

转载自blog.csdn.net/weixin_44568736/article/details/121795212