Unity PC和Android端的數據存儲和讀取

使用Resource:

提示:使用resouce打包后會被壓縮進.resources文件中,意味著它是只讀文件,且必須使用resouce.load加載:

    /// <summary>/// 全平臺使用/// </summary>/// <typeparam name="T"></typeparam>/// <param name="fileName"></param>/// <returns></returns>static public T LoadJsonOnResource<T>(string fileName){Debug.Log("我是Resources讀取");string json = "";TextAsset text = Resources.Load<TextAsset>("Jsons/" + fileName);json = text.text;Debug.Log("json: " + json);if (string.IsNullOrEmpty(json)){Debug.LogWarning("this json is null !");return default(T);}T result = JsonUtility.FromJson<T>(json);return result;}

PC端寫入

    /// <summary>/// 僅支持Windows平臺寫入/// </summary>/// <typeparam name="T"></typeparam>/// <param name="path"></param>/// <param name="fileName"></param>/// <param name="info"></param>static public void SaveJsonOnWin<T>(PathType path, string fileName, T info){string url = "";if (path == PathType.ResourcePath){url = Application.dataPath + "/Resources/Jsons/" + fileName;}else if (path == PathType.StreamingAssetsPath){url = Application.streamingAssetsPath + "/" + fileName;}else{url = Application.dataPath + "/" + fileName;}Debug.Log("url:     " + url);if (File.Exists(url)){File.Delete(url);}File.Create(url).Dispose();//這里不加dispose會報錯,很重要string json = JsonUtility.ToJson(info);Debug.Log("json: " + json);try{StreamWriter sw = new StreamWriter(url);sw.WriteLine(json);sw.Close();Debug.Log("寫入成功");}catch (Exception){Debug.Log("json出錯");}}

PC端讀取:

    static public T LoadJsonOnWinPath<T>(PathType path, string fileName){string url = "";if (path == PathType.StreamingAssetsPath){url = Application.streamingAssetsPath + "/" + fileName;Debug.Log("我是StreamingAssetsPath讀取\n" + url);}else{url = Application.dataPath + "/" + fileName;Debug.Log("我是NormalPath讀取\n" + url);}if (!File.Exists(url)){Debug.LogWarning("path is null !     " + fileName);return default(T);}StreamReader sr = new StreamReader(url);string json = sr.ReadToEnd();Debug.Log("json: " + json);T result = default(T);if (!string.IsNullOrEmpty(json)){result = JsonUtility.FromJson<T>(json);}sr.Close();return result;}

Android端寫入:

提示: PersistentDataPath使用該路徑寫入

    /// <summary>/// android平臺只有該路徑支持寫入/// </summary>/// <typeparam name="T"></typeparam>/// <param name="path"></param>/// <param name="fileName"></param>/// <param name="info"></param>static public void SaveJsonOnAndroid<T>(string fileName, T info){string url = Path.Combine(Application.persistentDataPath, fileName);Debug.Log("我是PersistentDataPath存儲\n" + url);StreamWriter sw = null;if (!File.Exists(url)){sw = File.CreateText(url);}string json = JsonUtility.ToJson(info);Debug.Log("json: " + json);sw.WriteLine(json);sw.Close();}

Android端讀取:

    static public T LoadJsonOnAndroid<T>(PathType path, string file){string url = "";if (path == PathType.PersistentDataPath){url = Application.persistentDataPath + "/" + file;Debug.Log("我是PersistentDataPath讀取\n" + url);}string json = "";if (File.Exists(url)){try{FileStream fileStream = new FileStream(url, FileMode.OpenOrCreate);StreamReader sr = new StreamReader(fileStream, Encoding.UTF8);json = sr.ReadToEnd();Debug.Log("fileStream   json: " + json);T result = default(T);if (!string.IsNullOrEmpty(json)){result = JsonUtility.FromJson<T>(json);}sr.Close();return result;}catch{Debug.LogFormat("url:   {0} error or stream error", url);}}else{Debug.LogError("file not exist  " + url);}return default(T);}

注意:Android端的StreamingAssets讀取不能使用該方法讀取。

最后附上完整代碼

using System;
using System.IO;
using System.Text;
using UnityEngine;
using Debug = UnityEngine.Debug;
public class JsonExtension
{/// <summary>/// 全平臺使用/// </summary>/// <typeparam name="T"></typeparam>/// <param name="fileName"></param>/// <returns></returns>static public T LoadJsonOnResource<T>(string fileName){Debug.Log("我是Resources讀取");string json = "";TextAsset text = Resources.Load<TextAsset>("Jsons/" + fileName);json = text.text;Debug.Log("json: " + json);if (string.IsNullOrEmpty(json)){Debug.LogWarning("this is jsons is null !");return default(T);}T result = JsonUtility.FromJson<T>(json);return result;}/// <summary>/// 僅支持Windows平臺寫入/// </summary>/// <typeparam name="T"></typeparam>/// <param name="path"></param>/// <param name="fileName"></param>/// <param name="info"></param>static public void SaveJsonOnWin<T>(PathType path, string fileName, T info){string url = "";if (path == PathType.ResourcePath){url = Application.dataPath + "/Resources/Jsons/" + fileName;}else if (path == PathType.StreamingAssetsPath){url = Application.streamingAssetsPath + "/" + fileName;}else{url = Application.dataPath + "/" + fileName;}Debug.Log("url:     " + url);if (File.Exists(url)){File.Delete(url);}File.Create(url).Dispose();string json = JsonUtility.ToJson(info);Debug.Log("json: " + json);try{StreamWriter sw = new StreamWriter(url);sw.WriteLine(json);sw.Close();Debug.Log("寫入成功");}catch (Exception){Debug.Log("json出錯");}//sw.Flush();//FileStream fs = new FileStream(url, FileMode.OpenOrCreate);//byte[] byteArray = Encoding.UTF8.GetBytes(info);//foreach (var by in byteArray)//{//    fs.WriteByte(by);//}}static public T LoadJsonOnWinPath<T>(PathType path, string fileName){string url = "";if (path == PathType.StreamingAssetsPath){url = Application.streamingAssetsPath + "/" + fileName;Debug.Log("我是StreamingAssetsPath讀取\n" + url);}else{url = Application.dataPath + "/" + fileName;Debug.Log("我是NormalPath讀取\n" + url);}if (!File.Exists(url)){Debug.LogWarning("path is null !     " + fileName);return default(T);}StreamReader sr = new StreamReader(url);string json = sr.ReadToEnd();Debug.Log("json: " + json);T result = default(T);if (!string.IsNullOrEmpty(json)){result = JsonUtility.FromJson<T>(json);}sr.Close();return result;}/// <summary>/// android平臺只有該路徑支持寫入/// </summary>/// <typeparam name="T"></typeparam>/// <param name="path"></param>/// <param name="fileName"></param>/// <param name="info"></param>static public void SaveJsonOnAndroid<T>(string fileName, T info){string url = Path.Combine(Application.persistentDataPath, fileName);Debug.Log("我是PersistentDataPath存儲\n" + url);StreamWriter sw = null;if (!File.Exists(url)){sw = File.CreateText(url);}string json = JsonUtility.ToJson(info);Debug.Log("json: " + json);sw.WriteLine(json);sw.Close();}static public T LoadJsonOnAndroid<T>(PathType path, string file){string url = "";if (path == PathType.PersistentDataPath){url = Application.persistentDataPath + "/" + file;Debug.Log("我是PersistentDataPath讀取\n" + url);}string json = "";if (File.Exists(url)){try{FileStream fileStream = new FileStream(url, FileMode.OpenOrCreate);StreamReader sr = new StreamReader(fileStream, Encoding.UTF8);json = sr.ReadToEnd();Debug.Log("fileStream   json: " + json);T result = default(T);if (!string.IsNullOrEmpty(json)){result = JsonUtility.FromJson<T>(json);}sr.Close();return result;}catch{Debug.LogFormat("url:   {0} error or stream error", url);}}else{Debug.LogError("file not exist  " + url);}return default(T);}public enum PathType{ResourcePath,StreamingAssetsPath,PersistentDataPath,NormalPath}
}
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;public class TestJson : MonoBehaviour
{#region Windowspublic Button btn1;public Button btn2;public Button btn3;public Button btn4;#endregion#region Androidpublic Button btn5;public Button btn6;public Button btn7;public Button btn8;#endregionpublic GameObject[] WinBtns;public GameObject[] AndroidBtns;void Start(){MyJsonData data1 = new MyJsonData(10, "alibaba", Vector3.one);MyJsonData data2 = new MyJsonData(20, "tx", Vector3.one);if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer){for (int i = 0; i < WinBtns.Length; i++){WinBtns[i].gameObject.SetActive(true);}btn1.onClick.AddListener(() =>{JsonExtension.SaveJsonOnWin(JsonExtension.PathType.ResourcePath, "test1.json", data1);});btn2.onClick.AddListener(() =>{JsonExtension.SaveJsonOnWin(JsonExtension.PathType.StreamingAssetsPath, "test2.json", data1);});btn3.onClick.AddListener(() =>{JsonExtension.LoadJsonOnResource<MyJsonData>("test1");});btn4.onClick.AddListener(() =>{JsonExtension.LoadJsonOnWinPath<MyJsonData>(JsonExtension.PathType.StreamingAssetsPath, "test2.json");});}if (Application.platform == RuntimePlatform.Android){for (int i = 0; i < AndroidBtns.Length; i++){AndroidBtns[i].gameObject.SetActive(true);}btn5.onClick.AddListener(() =>{JsonExtension.SaveJsonOnAndroid("test3.json", data2);});btn6.onClick.AddListener(() =>{JsonExtension.LoadJsonOnResource<MyJsonData>("test1");});btn7.onClick.AddListener(() =>{//直接讀會報錯,必須使用UnityWebRequest讀取//je.LoadJsonOnAndroid<MyJsonData>(JsonExtension.PathType.StreamingAssetsPath, "test2.json");StartCoroutine(LoadFromStreamingAssets(Application.streamingAssetsPath + "/test2.json"));});btn8.onClick.AddListener(() =>{JsonExtension.LoadJsonOnAndroid<MyJsonData>(JsonExtension.PathType.PersistentDataPath, "test3.json");});}}IEnumerator LoadFromStreamingAssets(string url){using (UnityWebRequest request = UnityWebRequest.Get(url)){yield return request.SendWebRequest();if (request.isDone){if (request.isNetworkError || request.isHttpError){Debug.Log(request.error);}else{Debug.Log("我是UnityWebRequest讀取安卓");string androidJson = request.downloadHandler.text;Debug.Log("androidJson: " + androidJson);/** 對json做處理*/}}}}
}[Serializable]
public class MyJsonData
{public int id;public string name;public Vector3 pos;public MyJsonData(int id, string name, Vector3 pos){this.id = id;this.name = name;this.pos = pos;}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/40124.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/40124.shtml
英文地址,請注明出處:http://en.pswp.cn/web/40124.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

論文學習——動態多目標優化的一種新的分位數引導的對偶預測策略

論文題目&#xff1a;A novel quantile-guided dual prediction strategies for dynamic multi-objective optimization 動態多目標優化的一種新的分位數引導的對偶預測策略&#xff08;Hao Sun a,b, Anran Cao a,b, Ziyu Hu a,b, Xiaxia Li a,b, Zhiwei Zhao c&#xff09;In…

“免費”的可視化大屏案例分享-智慧園區綜合管理平臺

一.智慧園區是什么&#xff1f; 智慧園區是一種融合了新一代信息與通信技術的先進園區發展理念。它通過迅捷信息采集、高速信息傳輸、高度集中計算、智能事務處理和無所不在的服務提供能力&#xff0c;實現了園區內及時、互動、整合的信息感知、傳遞和處理。這樣的園區旨在提高…

自定義注解-手機號驗證注解

注解 package com.XX.assess.annotation;import com.XX.assess.util.MobileValidator;import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.*;/*** 手機號校驗注解* @author super*/ @Retention(RetentionPolicy.RUNTIME) @Ta…

正確使用Pytorch Geometric打開Cora(Planetoid)數據集

文章目錄 關于報錯&#xff08;"Cannot connect to host"&#xff09;解決方法 關于報錯&#xff08;“Cannot connect to host”&#xff09; 我們在使用PyG調用Planetoid數據集的時候&#xff0c;常會碰到如下報錯&#xff1a; 解決方法就是手動下載這個數據集。…

在 AWS Lambda 中使用 Flask 應用

本文將介紹如何在 AWS Lambda 中創建和部署一個使用 Flask 框架的應用。 1. 創建 Lambda 函數 首先,在 AWS Lambda 控制臺創建一個新的函數,命名為 ??flask-app??。 2. 準備 Flask 層 為了在 Lambda 中使用 Flask,我們需要創建一個包含 Flask 庫的層。按照以下步驟操…

java中如何使用ffmpeg命令來實現視頻編碼轉換

在Java中使用FFmpeg命令來進行視頻編碼轉換&#xff0c;可以通過調用系統命令來執行FFmpeg命令。下面是一個使用FFmpeg進行視頻轉碼的示例代碼&#xff1a; import java.io.BufferedReader; import java.io.InputStreamReader;public class FFmpegVideoConverter {public stat…

前端播放RTSP視頻流,使用FLV請求RTSP視頻流播放(Vue項目,在Vue中使用插件flv.js請求RTSP視頻流播放)

簡述&#xff1a;在瀏覽器中請求 RTSP 視頻流并進行播放時&#xff0c;直接使用原生的瀏覽器 API 是行不通的&#xff0c;因為它們不支持 RTSP 協議。為了解決這個問題&#xff0c;開發者通常會選擇使用像 flv.js 這樣的庫&#xff0c;它專為在瀏覽器中播放 FLV 和其他流媒體格…

MySQL 代理層:ProxySQL

文章目錄 說明安裝部署1.1 yum 安裝1.2 啟停管理1.3 查詢版本1.4 Admin 管理接口 入門體驗功能介紹3.1 多層次配置系統 讀寫分離將實例接入到代理服務定義主機組之間的復制關系配置路由規則事務讀的配置延遲閾值和請求轉發 ProxySQL 核心表mysql_usersmysql_serversmysql_repli…

Java實現日志全鏈路追蹤.精確到一次請求的全部流程

廣大程序員在排除線上問題時,會經常遇見各種BUG.處理這些BUG的時候日志就格外的重要.只有完善的日志才能快速有效的定位問題.為了提高BUG處理效率.我決定在日志上面優化.實現每次請求有統一的id.通過id能獲取當前接口的全鏈路流程走向. 實現效果如下: 一次查詢即可找到所有關…

自定義一個背景圖片的高度,隨著容器高度的變化而變化,小于圖片的高度時裁剪,大于時拉伸100%展示

1、通過js創建<image?>標簽來獲取背景圖片的寬高比&#xff1b; 2、當元素的高度大于原有比例計算出來的高度時&#xff0c;背景圖片的高度拉伸自適應100%&#xff0c;否則高度為auto&#xff0c;會自動被裁減 3、背景圖片容器高度變化時&#xff0c;自動計算背景圖片的…

Android network - NUD檢測機制(Android 14)

Android network - NUD檢測機制 1. 前言2. 源碼分析2.1 ClientModeImpl2.2 IpClient2.3 IpReachabilityMonitor 1. 前言 在Android系統中&#xff0c;NUD&#xff08;Neighbor Unreachable Detection&#xff09;指的是網絡中的鄰居不可達檢測機制&#xff0c;它用于檢測設備是…

數據驅動測試實踐:Postman 中使用數據文件的指南

Postman 是一個強大的 API 開發和測試工具&#xff0c;它支持數據驅動測試&#xff0c;允許測試者使用外部數據文件來驅動測試&#xff0c;實現測試用例的參數化。數據驅動測試可以顯著提高測試效率&#xff0c;減少重復工作&#xff0c;并允許測試用例覆蓋更廣泛的輸入場景。本…

一文了解常見DNS問題

當企業的DNS出現故障時&#xff0c;為不影響企業的正常運行&#xff0c;團隊需要能夠快速確定問題的性質和范圍。那么有哪些常見的DNS問題呢&#xff1f; 域名解析失敗&#xff1a; 當您輸入一個域名&#xff0c;但無法獲取到與之對應的IP地址&#xff0c;導致無法訪問相應的網…

【代碼隨想錄算法訓練營第五十九天|卡碼網110.字符串接龍、105.有向圖的完全可達性、106.島嶼的周長】

文章目錄 卡碼網110.字符串接龍105.有向圖的完全可達性106.島嶼的周長 卡碼網110.字符串接龍 這題是在字符串上進行廣搜&#xff0c;字符串廣搜是對一個字符串按照位置來搜索&#xff0c;與原字符串只有一個位置字符不同那么就是在原字符串的基礎上距離加1。因此需要一個字典來…

獲取VC賬號,是成為亞馬遜供應商的全面準備與必要條件

成為亞馬遜的供應商&#xff0c;擁有VC&#xff08;Vendor Central&#xff09;賬號&#xff0c;是眾多制造商和品牌所有者的共同目標。這不僅代表了亞馬遜對供應商的高度認可&#xff0c;也意味著獲得了更多的銷售機會和更廣闊的市場前景。 全面準備與必要條件是獲取VC賬號的關…

代碼轉換成AST語法樹移除無用代碼console.log、import

公司中代碼存在大量,因此產生 可以使用 @babel/parser 解析代碼生成 AST (抽象語法樹),然后使用 @babel/traverse 進行遍歷并刪除所有的 console.log 語句,最后使用 @babel/generator 生成修改后的代碼。 這里有一個網址,可以線上解析代碼轉換成AST語法樹: https://astex…

Python爬蟲康復訓練——筆趣閣《神魂至尊》

還是話不多說&#xff0c;很久沒寫爬蟲了&#xff0c;來個bs4康復訓練爬蟲&#xff0c;正好我最近在看《神魂至尊》&#xff0c;爬個txt文件下來看看 直接上代碼 """ 神魂至尊網址-https://www.bqgui.cc/book/1519/ """ import requests from b…

【C++】 解決 C++ 語言報錯:未定義行為(Undefined Behavior)

文章目錄 引言 未定義行為&#xff08;Undefined Behavior, UB&#xff09;是 C 編程中非常危險且難以調試的錯誤之一。未定義行為發生時&#xff0c;程序可能表現出不可預測的行為&#xff0c;導致程序崩潰、安全漏洞甚至硬件損壞。本文將深入探討未定義行為的成因、檢測方法…

零基礎STM32單片機編程入門(七)定時器PWM波輸出實戰含源碼視頻

文章目錄 一.概要二.PWM產生框架圖三.CubeMX配置一個TIME輸出1KHZ&#xff0c;占空比50%PWM波例程1.硬件準備2.創建工程3.測量波形結果 四.CubeMX工程源代碼下載五.講解視頻鏈接地址六.小結 一.概要 脈沖寬度調制(PWM)&#xff0c;是英文“Pulse Width Modulation”的縮寫&…

通過營銷本地化解鎖全球市場

在一個日益互聯的世界里&#xff0c;企業必須接觸到全球各地的不同受眾。營銷本地化是打開這些全球市場的關鍵。它包括調整營銷材料&#xff0c;使其與不同地區的文化和語言細微差別產生共鳴。以下是有效的營銷本地化如何推動您的全球擴張&#xff0c;并用實際例子來說明每一點…