using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
/*******************************************************************************
*Create By CG
*Function txt文件操作
*******************************************************************************/
namespace CG.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);
}
}
}
///
/// 给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)
{
WDebug.LogError("WriteAllTxt Erro :" + ex.Message);
return;
}
}
///
/// 读取txt文件中所有内容(适宜小数据量)
///
/// txt文件路径
/// 读取到的所有内容
public static void ReadAllTxt(string txtFilePath, System.Action actionResult)
{
//return File.ReadAllText(txtFilePath);
MonoManager.Instance.StartCoroutine(GetTextAsyn(txtFilePath, actionResult));
}
private static IEnumerator GetTextAsyn(string url, System.Action actionResult)
{
UnityWebRequest request = UnityWebRequest.Get(url);
yield return request.SendWebRequest();
string t = request.downloadHandler.text;
if (string.IsNullOrEmpty(t)) WDebug.LogError("GetTextAsyn()/ Get Text is error! url:" + url);
actionResult?.Invoke(t);
}
///
/// 读取txt文件中所有内容
///
/// txt文件路径
/// 读取到的所有行列内容
public static string[] ReadAllLines(string txtFilePath)
{
WDebug.Log("Path:" + 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)
{
WDebug.LogError("ReadBigTxt Erro :" + ex.Message);
return null;
}
return list.ToArray();
}
}
}