1、StreamWriter和StreamReader 流写入和读取
public void CreatFile(string path)
{
if (!System.IO.File.Exists(path))
{
WriteFile(path);
}
}
/// <summary>
/// path需要包含文件的后缀名
/// </summary>
/// <param name="path">路径</param>
/// <param name="con">需要写入的数据</param>
public void WriteFile(string path, string con = "")
{
string str = con;
//若是直接在文件里添加数据,则采用重写方法,将append设置为true
var file = new StreamWriter(path, true);
//var file = new StreamWriter(path);
//file.WriteLine(str);
file.Write(str);
file.Close();
}
/// <summary>
/// path需要包含文件的后缀名
/// </summary>
/// <param name="path"></param>
public void ReadFile(string path)
{
using (StreamReader file = new StreamReader(path))
{
string fileContents = file.ReadToEnd();
Debug.Log("读取文件内容:" + fileContents);
file.Close();
}
}
2 、WWW读取文件,当文件属于StreamingAssets文件夹时,可直接读取txt和xlsx,以及csv
//地址前面需要加上file://
path = "file://" + Application.streamingAssetsPath + "/test.txt";
ReadByWWW(path);
public void ReadByWWW(string path)
{
StartCoroutine(LoadWWW(path));
}
IEnumerator LoadWWW(string path)
{
WWW ww = new WWW(path);
yield return ww;
if (ww.error == null)
{
Debug.Log("" + ww.text.ToString());
}
else
{
Debug.Log(ww.error.ToString());
}
}
3、
打开文件,直接用FileStream,若是没有该文件则直接创建,path都需加后缀名
public void OpenFile(string path)
{
FileStream aFile = new FileStream(path, FileMode.OpenOrCreate);
using (StreamReader file = new StreamReader(aFile))
{
string fileContents = file.ReadToEnd();
Debug.Log("读取文件内容:" + fileContents);
file.Close();
}
}
public void WriteFile(string path)
{
FileStream aFile = new FileStream(path, FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(aFile);
sw.WriteLine("写入测试");
sw.Close();
}