unity3D技术分享

Unity-Application.temporaryCache

2023-12-11  本文已影响0人  好怕怕

主要实现,向缓冲区写入指定数量的文件,达到上限后清理最早的缓存文件(demo代码,测试为主)

image.png

安卓目录

temporaryCachePath:/storage/emulated/0/Android/data/com.DetaultCompany.TemporarvCacheDemo/cache

PC目录

temporaryCachePath:C:/Users/admin/AppData/Local/Temp/DefaultCompany/TemporaryCacheDemo


using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
using Random = UnityEngine.Random;

public class UiAsset
{
    public List<string> Pahts;
}


public class TestDemo : MonoBehaviour
{

    public Button writeBtn;
    public Button readBtn;
    public Button clearBtn;

    private string CacheFolder = "CacheFolder";
    private string CacheDir;

    private string AssetFileName = "UiAsset";

    /// <summary>
    /// 最大缓存数量
    /// </summary>
    public int CacheCount = 10;

    void Awake()
    {
        string temporaryCachePath = Application.temporaryCachePath;
        CacheDir = temporaryCachePath + "/" + CacheFolder;

        Debug.LogError("temporaryCachePath:" + temporaryCachePath);

        writeBtn.onClick.AddListener(OnWrite);
        readBtn.onClick.AddListener(OnRead);
        clearBtn.onClick.AddListener(OnClear);

    }


    private void OnWrite()
    {
        Debug.LogError("开始写入文件");

        UiAsset asset = GetAsset();
        // 创建单个资源文件

        string fileName = Random.Range(1, 20).ToString();
        string fileHash = fileName.GetHashCode().ToString();
        string filePath = GetFilePath(fileHash);
        Debug.LogError(fileName + "," + fileHash + ",缓存文件:" + filePath);

        byte[] fileBytes = new[] { (byte)Random.Range(0, 200), (byte)Random.Range(0, 200), (byte)Random.Range(0, 200) };
        AddFile(asset, filePath, fileHash, fileBytes);

        // 总文件落地
        string json = JsonUtility.ToJson(asset);
        string path = GetFilePath(AssetFileName);
        // 覆盖写入总配置
        File.WriteAllText(path, json);
        Debug.LogError("写入完成!");
    }

    private void AddFile(UiAsset asset, string filePath, string fileHash, byte[] fileBytes)
    {
        // 覆盖旧文件写入新文件
        File.WriteAllBytes(filePath, fileBytes);

        // 如果存在当前文件,移除旧数据,新数据放到最后
        var oldIndex = asset.Pahts.IndexOf(fileHash);
        if (!oldIndex.Equals(-1))
        {
            asset.Pahts.RemoveAt(oldIndex);
        }
        // 新的加入
        asset.Pahts.Add(fileHash);

        // 超出缓存文件清理
        if (asset.Pahts.Count > CacheCount)
        {
            // 清理最早加入的文件
            string removeFileName = asset.Pahts[0];
            asset.Pahts.RemoveAt(0);
            string removePath = GetFilePath(removeFileName);
            if (File.Exists(removePath))
            {
                File.Delete(removePath);
                Debug.LogError("超出缓存,清理文件:" + removePath);
            }
        }
    }


    private UiAsset GetAsset()
    {
        if (!Directory.Exists(CacheDir))
        {
            Directory.CreateDirectory(CacheDir);
            Debug.LogError("创建目录:" + CacheDir);
        }
        UiAsset asset = null;
        string path = GetFilePath(AssetFileName);
        if (File.Exists(path))
        {
            string text = File.ReadAllText(path);
            asset = JsonUtility.FromJson<UiAsset>(text);
        }
        else
        {
            asset = new UiAsset
            {
                Pahts = new List<string>()
            };
        }
        return asset;
    }



    private void OnRead()
    {
        var asset = GetAsset();
        Debug.LogError("读取完成:" + asset.Pahts.Count);
        for (int i = 0; i < asset.Pahts.Count; i++)
        {
            Debug.LogError(asset.Pahts[i]);
            var filePath = GetFilePath(asset.Pahts[i]);
            if (File.Exists(filePath))
            {
                var bytes = File.ReadAllBytes(filePath);
                string str = Encoding.Default.GetString(bytes);
                Debug.LogError(str);
            }
        }
    }

    /// <summary>
    /// 清理缓存的assetUi文件夹
    /// </summary>
    private void OnClear()
    {
        if (Directory.Exists(CacheDir))
        {
            Directory.Delete(CacheDir, true);
        }
    }

    private string GetFilePath(string fileName)
    {
        string path = CacheDir + "/" + fileName;
        return path;
    }



}


image.png image.png
上一篇 下一篇

猜你喜欢

热点阅读