失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > Unity | 安卓 读取和写入TXT文本操作

Unity | 安卓 读取和写入TXT文本操作

时间:2024-02-10 16:24:02

相关推荐

Unity | 安卓 读取和写入TXT文本操作

Unity在Android端PC端以及编辑器环境下读取并写入文本的操作,直接上代码

创建并写入文本内容

//创建并写入fileName为文件名称(记得加后缀)content为需要写入的文本内容public void CreateFileInPersistentData(string fileName,string content){string path = Application.persistentDataPath + "/" + fileName;if (File.Exists(path)){return;}else{FileStream fs = new FileStream(path, FileMode.Create); fs.Close();WriteTXT(fileName, content); }}

写入文本内容

public void WriteTXT(string fileName, string s){string url = "";if (Application.platform == RuntimePlatform.Android){url = Application.persistentDataPath + "/" + fileName;File.WriteAllText(url, s);}else if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer){url = Application.persistentDataPath + "/" + fileName;FileStream fs = new FileStream(url, FileMode.Open);byte[] bytes = new UTF8Encoding().GetBytes(s.ToString());fs.Write(bytes, 0, bytes.Length);fs.Close();}}

读取文本内容

public string LoadTXTtoString(string fileName){string url = Application.persistentDataPath + "/" + fileName;string s = "";if (Application.platform == RuntimePlatform.Android){s = File.ReadAllText(url);}else if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer){FileStream fs = new FileStream(url, FileMode.Open);byte[] bytes = new byte[100];fs.Read(bytes, 0, bytes.Length);//将读取到的二进制转换成字符串s = new UTF8Encoding().GetString(bytes);fs.Close();}return s;}

调用方法演示

public Text show_text;public Button ok_btn;private void Awake(){CreateFileInPersistentData("test.txt", "这是一个测试文本..."); }private void Start(){ok_btn.onClick.AddListener(() => {show_text.text = LoadTXTtoString("test.txt"});}

如果觉得《Unity | 安卓 读取和写入TXT文本操作》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。