using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.Networking; /******************************************************************************* *Create By CG *Function txt文件操作 *******************************************************************************/ namespace ZXK.UTility { public static class TxtFileHandle { /// /// 给txt文件添加内容,如果没有文件无法写入 /// /// 文件路径 /// 需要添加的内容 /// 是否替换原有文件 public static void WriteAllTxt(string txtFilePath, string contents,bool replace) { if (!File.Exists(txtFilePath)) return; if (replace) { File.WriteAllText(txtFilePath, contents); } else { using (StreamWriter file = new StreamWriter(txtFilePath, true)) { file.WriteLine(contents); } } } /// /// 将数据存入prefs /// /// /// public static void WriteAllTxtByPrefs(string key, string contents) { PlayerPrefs.SetString(key, contents); } /// /// 给txt文件添加多条内容,如果没有文件则创建文件写入 /// /// 文件路径 /// 需要添加的内容 /// 是否替换原有文件 public static void WriteAllTxt(string txtFilePath, string[] contents, bool replace) { try { using (StreamWriter file = new StreamWriter(txtFilePath, !replace)) { for (int i = 0; i < contents.Length; i++) { file.WriteLine(contents[i]); } } } catch (System.Exception ex) { Debug.LogError("WriteAllTxt Erro :" + ex.Message); return; } } /// /// 读取txt文件中所有内容(适宜小数据量) /// /// txt文件路径 /// 读取到的所有内容 public static string ReadAllTxt(string txtFilePath) { return File.ReadAllText(txtFilePath); } /// /// 加载Resource路径下文本文档 /// /// 相对于Resource文件夹路径 /// public static string ReadAllTxtByResource(string txtFilePath) { return Resources.Load(txtFilePath).text; } /// /// 加载prefs下内容 /// /// /// public static string ReadAllTxtByPrefs(string key) { return PlayerPrefs.GetString(key,""); } /// /// 读取txt文件中所有内容 /// /// txt文件路径 /// 读取到的所有行列内容 public static string[] ReadAllLines(string txtFilePath) { return File.ReadAllLines(txtFilePath); } /// /// 读取txt文件中所有内容(适宜大数据量) /// /// txt文件路径 /// 读取到的所有行列内容 public static string[] ReadBigTxt(string txtFilePath) { List list = new List(); try { using (StreamReader sr = new StreamReader(txtFilePath)) { while (!sr.EndOfStream) { string readData = sr.ReadLine(); list.Add(readData); } } } catch (System.Exception ex) { Debug.LogError("ReadBigTxt Erro :" + ex.Message); return null; } return list.ToArray(); } } }